https://rentry.org/PPP2_p146

// Code derived from Stroustrup's PPP2 book
// § 5.5.3 Error reporting
//  -and beginning on p 146

#include <iostream>
#include <stdexcept>

using std::cout;
using std::runtime_error;

void error(const char* s) { throw runtime_error(s); }

// calculate area of a rectangle;
// return –1 to indicate a bad argument
int area(int length, int width)
{
  if (length <= 0 || width <= 0)
    return -1;

  return length * width;
}

// calculate area within frame
int framed_area(int x, int y)
{
  constexpr int frame_width = 2;

  if (x - frame_width <= 0 || y - frame_width <= 0)
    return -1;

  return area(x - frame_width, y - frame_width);
}

int f(int x, int y, int z)
{
  int area1 = area(x, y);

  if (area1 <= 0)
    error("non-positive area");

  int    area2 = framed_area(1, z);
  int    area3 = framed_area(y, z);
  double ratio = double(area1) / area3;

  // . . .

  cout << area1 << '\n'  //
       << area2 << '\n'  //
       << area3 << '\n'  //
       << ratio << '\n';

  return area3;  // stub (ie, 'a temp placeholder/value/etc'; here as a return)
}

int main()
{
  int x = 0;  // please test out some positive values here, too
  int y = 0;  //
  int z = 0;  //

  int foo = f(x, y, z);

  cout << foo << '\n';
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_05/main_p146.cpp && ./a.out

PrevUpNext

Edit
Pub: 22 Feb 2023 09:46 UTC
Edit: 29 Apr 2023 09:21 UTC
Views: 340