liveBook · Manning

Signed integer arithmetic

As explained in Modern C

Signed integer arithmetic is arithmetic performed on C integer operands whose types represent negative as well as non-negative values.

Signed integer arithmetic uses integer representations that can denote negative and non-negative values. In two’s-complement representation, the same bit operation used for unsigned negation applies, but a high-order bit is interpreted as negative. section 5.7.5

A deceptively similar loop

for (unsigned i = 1; i; ++i) do_something(); for (signed i = 1; i; ++i) do_something(); The unsigned counter eventually wraps to zero. The signed counter can overflow instead; signed overflow has undefined behavior, so the compiler may assume it never occurs and optimize the second loop into an infinite loop. section 5.7.5

TAKEAWAY

  • Treat signed overflow as undefined behavior, not as predictable wraparound. section 5.7.5
  • Do not infer post-overflow execution: once execution reaches an undefined state, later behavior has no guaranteed continuation. section 5.7.5

How Modern C covers it

How deep it goes
Connects two’s-complement bit operations to compiler optimization, but focuses on overflow consequences rather than a complete representation taxonomy.
Examples
Uses negation of 240, paired signed and unsigned counter loops, and an optimized infinite-loop consequence.
What it assumes
Assumes familiarity with unsigned arithmetic, bitwise complement, and integer counter loops.
What you can do after
Diagnose signed-overflow hazards and avoid treating their results as predictable wraparound.
How it connects
Connects signed arithmetic with unsigned arithmetic, two’s-complement representation, undefined behavior, and compiler optimization.

Also explained in

Compare how 2 books explain signed integer arithmetic →

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