Signed arithmetic overflow occurs when a signed integer operation exceeds the representable range. Unlike unsigned arithmetic, which wraps around, signed overflow has undefined behavior in C. Two’s-complement representation uses the same bit operations as unsigned integers but interprets the high-order bit as negative. section 5.7.5
TAKEAWAY rules:
- Do not infer a predictable wrapped result from signed overflow. section 5.7.5
- Account for compiler assumptions: once overflow would occur, the compiler may assume that undefined state is unreachable. section 5.7.5
for (unsigned i = 1; i; ++i) do_something(); for ( signed i = 1; i; ++i) do_something();
Compare unsigned and signed counter loops: the unsigned counter eventually wraps to zero, while the signed loop may be optimized as infinite because overflow is undefined. section 5.7.5
while (true) do_something();
The optimized signed-loop form illustrates the compiler’s permitted conclusion when it assumes signed overflow never occurs. section 5.7.5
