Positive integers that multiply to a negative value

前端 未结 9 1056
礼貌的吻别
礼貌的吻别 2021-02-07 05:17

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

9条回答
  •  再見小時候
    2021-02-07 05:39

    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 requirements

    2 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.

提交回复
热议问题