https://rentry.org/PPP2_p143a

// Code derived from Stroustrup's PPP2 book
// § 5.5.1 The caller deals with errors
//  -and beginning on p 143

#include <iostream>
#include <stdexcept>

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

// error() simply disguises throws
void error(const char* s) { throw runtime_error(s); }

constexpr int frame_width = 2;

// calculate area of a rectangle
int area(int length, int width) { return length * width; }

// calculate area within frame
int framed_area(int x, int y) { return area(x - frame_width, y - frame_width); }

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

  if (1 - frame_width <= 0 || z - frame_width <= 0)
    error("non-positive argument for area() called by framed_area()");

  int area2 = framed_area(1, z);

  if (y - frame_width <= 0 || z - frame_width <= 0)
    error("non-positive argument for area() called by framed_area()");

  int area3 = framed_area(y, z);

  cout << y << '\n'      //
       << z << '\n'      //
       << area2 << '\n'  //
       << area3 << '\n';
}

build & run:

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

PrevUpNext

Edit
Pub: 21 Feb 2023 07:54 UTC
Edit: 29 Apr 2023 09:13 UTC
Views: 421