https://rentry.org/PPP2_p142a

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

#include <iostream>
#include <stdexcept>

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

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

// 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 - 2, y - 2); }

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

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

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

  int area1 = area(x, y);

  cout << x << '\n'  //
       << y << '\n'  //
       << area1 << '\n';
}

build & run:

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

PrevUpNext

Edit
Pub: 20 Feb 2023 11:32 UTC
Edit: 29 Apr 2023 09:08 UTC
Views: 606