liveBook · Manning

Signed arithmetic overflow

As explained in Modern C, Third Edition

Signed arithmetic overflow is the condition in which a signed integer operation produces a result outside the range representable by its result type.

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

How Modern C, Third Edition covers it

How deep it goes
Defines undefined behavior and traces its compiler-optimization consequences through contrasting loops.
Examples
Uses paired signed and unsigned incrementing loops, plus an equivalent infinite-loop optimization.
What it assumes
Assumes unsigned wraparound and basic C loops while introducing signed interpretation and overflow behavior.
What you can do after
Evaluate/understand why compiler transformations can turn an apparently terminating signed loop into an infinite loop.
How it connects
Connects signed overflow to unsigned wraparound, two’s-complement representation, undefined behavior, and the as-if rule.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.