I am learning C++ by reading Stroustrup\'s \"Principles and Practice Using C++\".
In the section about pre- and post-conditions there is the following example of functio
Are there such possible values for integer that pre-conditions is ok but post-condition not?
Yes there's a number of input values, that can cause the post condition to fail. If e.g.
int a = length*width;
overflows the positive int
range (std::numeric_limits
) and the compiler implementation yields a negative value for this case.
As others noted in their answers, the situation that length*width
goes out of bounds from ]0-std::numeric_limits
is actually undefined behavior, and the post condition renders merely useless, because any value might need to be expected for a
.
The key point to fix this, is given in @Deduplicator's answer, the pre-condition needs to be improved.
As a lance for Bjarne Stroustrup's reasonings to give that example:
I assume he wanted to point out that such undefined behavior might lead to unexpected negative values in the post-condition and surprising results for a naive assumption checked with the pre-condition.