https://rentry.org/PPP2_p163

// Code derived from Stroustrup's PPP2 book
// § 5.10 Pre- and post-conditions
//  -and beginning on p 163

#include <iostream>
#include <stdexcept>

using std::cerr;
using std::exception;
using std::runtime_error;

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

// the arguments are positive and a < b < c
int my_complicated_function(int a, int b, int c)
{
  if (! (0 < a && a < b && b < c))  // ! means “not” and && means “and”
    error("bad arguments for mcf");

  // . . .

  return 1;  // stub
}

int main()
try {
  // int a = 1;
  // int b = 2;
  // int c = 3;

  int a = 3;
  int b = 2;
  int c = 1;

  my_complicated_function(a, b, c);

} catch (exception& e) {
  cerr << "error: " << e.what() << '\n';
  // keep_window_open();
  return 1;

} catch (...) {
  cerr << "Oops: unknown exception!\n";
  // keep_window_open();
  return 2;
}

build & run:

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

PrevUpNext

Edit
Pub: 25 Feb 2023 12:09 UTC
Edit: 29 Apr 2023 10:05 UTC
Views: 415