Positive integers that multiply to a negative value

前端 未结 9 1086
礼貌的吻别
礼貌的吻别 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:40

    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::max()) 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::max()[ 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.

提交回复
热议问题