Positive integers that multiply to a negative value

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

    The answer is that his precondition-check is incomplete. Even though it is too restrictive.
    He failed to include a check that the product can be represented instead of resulting in UB:

    int area(int length, int width) {
        // calculate area of a rectangle
        assert(length >= 0 && width >= 0 && (!width
            || std::numeric_limits::max() / width >= length));
        int a = length * width;
        assert(a >= 0); // Not strictly neccessary - the math is easy enough
        return a;
    }
    

提交回复
热议问题