Positive integers that multiply to a negative value

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

    So basically, positive values in multiplication ... result in Positive values but these may not actually fit the result type .

    Your precondition is not complete, and you postcondition is also invalid. Not only you can get negative values but also positive values that are just smaller than the input value, all you need is sufficiently large values as input such that the wrap around goes beyond zero, i.e. a long-wrap-around .

    You can use this :

    bool multiplication_is_safe(uint32_t a, uint32_t b) {
        size_t a_bits=highestOneBitPosition(a), b_bits=highestOneBitPosition(b);
        return (a_bits+b_bits<=32);
    }
    

    to guard against overflow, but then you would want to employ additional checks for FALSE-Positives .

    Alternatively if performance is not that much of an issue you can use MPZ library. If performance is an issue and you want to write assembly for a CPU that has an overflow flag, then you can do just that. It is possible that your compiler also can do the checks for you e.g. G++ has fno-strict-overflow or maybe cast to unsigned int after the precondition check.

    At any rate, most of these solutions do not actually solve your problem that results will be foo, that is that you might get smaller area than the actual result.

    So your only safe choice is to allow only safe multiplications as shown herein, doing that you miss something, but not that much.

提交回复
热议问题