Integer overflow (C++)

Unsigned integer

Range: [0,255]
Bitfield: 0x00 =++=> 0x01 =++=> ... =++=> 0xFF
Interpr.:    0 =++=>    1 =++=> ... =++=>  255

“Unsigned integers shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer.” (C++ Standard (N4713) – 6.7.1.4)

#include <stdint.h>

int main()
{
  uint8_t i = 255;
  i++; // definded behavior, i = 0 (= 256 % 2^8)
  return 0;
}

Signed integer
Signed Magnitude (old processors)

Range: [-127,127]
Bitfield: 0x00 =++=> ... =++=> 0x7F =++=> 0x80 =++=> ... =++=> 0XFF
Interpr.:   +0 =++=> ... =++=> +127 =++=>   -0 =++=> ... =++=> -127

One’s complement (old processors)

Range: [-127,127]
Bitfield: 0x00 =++=> ... =++=> 0x7F =++=> 0x80 =++=> ... =++=> 0XFF
Interpr.:   +0 =++=> ... =++=> +127 =++=> -127 =++=> ... =++=>   -0

Two’s complement (new processors)
–> Advantage: Basic arithmetic operations are identical to the unsigned ones.

Range: [-128,127]
Bitfield: 0x00 =++=> ... =++=> 0x7F =++=> 0x80 =++=> ... =++=> 0XFF
Interpr.: +/-0 =++=> ... =++=> +127 =++=> -128 =++=> ... =++=>   -1

“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.” (C++ Standard (N4713) – 8.1.4)

#include <stdint.h>

int main()
{
  int8_t i = 127;
  i++; // undefined behavior, but often i = -128 (2's comp.)
  return 0;
}

References
C++ Standard (N4713)