Positive integers that multiply to a negative value

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

    Multiplication of values that overflow the bit representation of value type is undefined because the number of bits overflowed could be more than 1. Thus you could end up with a positive or negative sign bit and the number of lost bits is variable.

    Example 1: INT_MAX * 2 : result is correct but since the high bit represents the sign bit it is not corrected represented for its type.

    Example 2: INT_MAX * 4 : 1 bit is lost to overflow and the the sign bit is incorrect like in the previous example.

    Example 3: (INT_MAX + 1) * 2 = 0 : due to overflow of all set bits but sign is correct.

    I am using a 8 bit binary representation to make it easier to read, to show why this happens.

    0111 1111              // Max positive signed value
    +1
    1000 0000              // Sign bit set but binary value is correct
    *2
    0000 0000              // Upper bit is lost due to overflow
    

    In this case there is both soft overflow, no lost information but the representation is incorrect. And hard overflow where the bit is no longer present in the result.

    The difference in the overflows is how the overflow can be detected. Typically hard overflows will be detected by the hardware and require very little work for the software to handle. However software overflows may require the software to explicitly test for the overflow condition because the hardware typically does not recognize a sign bit in integer math operations.

    How the run-time library handles the overflow is up to the library. Most will ignore it because it is faster to do so, while others may throw an error. Undefined behavior does not mean it might format your disk. The result of a math operation does not alter the flow of code in any way except as the logic of the code dictates. It can ignore the overflow or try to handle it in some way. The standard does not dictate what method to employ if the code or the hardware tries to handle the problem.

    Basically three there are 3 possible things that can happen.
    1. The overflow is ignore and the returned value in invalid.
    2. The overflow is ignored by the run-time library but the hardware throws an error that is also ignored, resulting in a hard failure of the running code. In this situation it is completely up to the OS to determine what happens next. Going nuts and destroying data would to a poor design decision.
    3. The overflow is handled by the run-time library which must determine the best way to proceed. Typically this means giving the code a chance to catch the error and handle it, or by shutting down the code as graceful as possible.

提交回复
热议问题