Search code examples
c++preconditionspost-conditions

Pre and Post Condition from Stroustrup's book


In chapter 5.10.1 of Programming: Principles and Practice using C++, there is a "Try this" exercise for debugging for bad input of an area. The pre-conditions are if the the inputs for length and width are 0 or negative while the post-condition is checking if the area is 0 or negative. To quote the problem, "Find a pair of values so that the pre-condition of this version of area holds, but the post-condition doesn’t.". The code so far is:

#include <iostream>
#include "std_lib_facilities.h"

int area (int length, int width) {
    if (length <= 0 || width <= 0) { error("area() pre-condition"); }
    int a =  length * width;
    if(a <= 0) { error("area() post-condition"); }
    return a;
}

int main() {

int a;
int b;
while (std::cin >> a >> b) {
    std::cout << area(a, b) << '\n';
}

system("pause");
return 0;
}

While the code appears to work, I can't wrap my head around what inputs will get the pre-condition to succeed yet will trigger the post-condition. So far I have tried entering strings into one of the inputs but that just terminates the program and tried looking up the ascii equivalent to 0, but same result as well. Is this supposed to be some sort of trick question or am I missing something?


Solution

  • Consider using large values for the input so that the multiplication overflows.