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
INT_MAX will fail to fulfill the post-condition when used for both length and width for all conforming compilers.
One might be tempted to say that, since the standard guarantees that INT_MAX
>=32767, then INT_MAX*INT_MAX
will always be greater than INT_MAX
and thus not representable in an int
which is defined as being able to hold a maximun value of INT_MAX
.
It is a good argument and it is actually what happens most often, you will get an overflow with most compilers.
But to cover all bases we need to be aware that the C++ standard states :
3.4.3
1 undefined behavior
behavior,upon use of a nonportable or erroneous program construct or of erroneous data,for which this International Standard imposes no requirements2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
3 EXAMPLE An example of undefined behavior is the behavior on integer overflow.
So it is a bit more serious than not getting the right value for the area. When INT_MAX
is used for both length and width (or any other combination with a result which is not representable) there is no guarantee of what the compiled program will do. Anything can happen; from the likely ones like overflows or crashes to the unlikely ones like disk formats.