Advertisement
Intermediate C++, Undefined Behavior

Why is signed integer overflow undefined but unsigned overflow defined?

Short answer

Unsigned overflow is defined to wrap modulo 2^n. Signed overflow is undefined because the standard doesn't fix a representation-independent result, and leaving it UB lets compilers optimize (e.g., assume x+1 > x).

Save C++ mock interview
Advertisement
AModel answer
Unsigned overflow is defined to wrap modulo 2^n. Signed overflow is undefined because the standard doesn't fix a representation-independent result, and leaving it UB lets compilers optimize (e.g., assume x+1 > x). This means relying on signed wraparound is unsafe; use unsigned types or explicit checks when wraparound semantics are needed.
int x = INT_MAX; x + 1;   // signed overflow: UB
unsigned u = UINT_MAX; u + 1; // defined: wraps to 0
Real-world example
An overflow check written as 'if (x + 1 < x)' is optimized away because signed overflow is UB.
Likely follow-ups
  • How does unsigned overflow behave? | Why does UB enable optimization here?
Related topics