Search code examples
c++binarylanguage-lawyerunsignedinteger-overflow

Does arithmetic overflow overwrite data?


std::uint8_t x = 256; //Implicitly converts to 0

std::uint8_t y = 255;
y++;

For x, I assume everything is handled because 100000000 gets converted to 00000000 using some defined conversion from int to uint8_t. x's memory should be 0 00000000 not 1 00000000.

However with y I believe the overflow stays in memory. y is initially 11111111. After adding 1, it becomes 1 00000000. This wraps around back to 0 because y only looks at the 8 LSB.

Does the 1 after y++; stay in memory, or is it discarded when the addition is done? If it is there, could it corrupt data before y?


Solution

  • Does arithmetic overflow overwrite data?

    The behaviour of signed arithmetic overflow is undefined. It's neither guaranteed to overwrite data, nor guaranteed to not overwrite data.

    std::uint8_t y = 255;
    y++;
    

    Unsigned overflow is well defined. y will be 0, and there are no other side-effects.


    Citation from the C++ standard (latest draft):

    [basic.fundamental]

    ... The range of representable values for the unsigned type is 0 to 2N−1 (inclusive); arithmetic for the unsigned type is performed modulo 2N.

    [Note 2: Unsigned arithmetic does not overflow. Overflow for signed arithmetic yields undefined behavior ([expr.pre]). — end note]


    [expr.pre]

    If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

    Since unsigned arithmetic is modular, the result can never be outside of representable values.