liveBook · Manning

Integer wraparound

As explained in Modern C

Unsigned wraparound is the reduction of an out-of-range unsigned arithmetic result into the representable range by modular reduction.

Unsigned wraparound reduces an out-of-range arithmetic result into the representable range by modular reduction. For size_t, arithmetic behaves as though it computes modulo SIZE_MAX + 1. section 4.1.2

A value crossing the boundary

For a size_t value, SIZE_MAX + 1 becomes 0, while 0 - 1 becomes SIZE_MAX. More generally, adding -1 to a value a produces a - 1 through wraparound. The same modular behavior explains clock calculations such as (8 + 6) % 12 == 2 and minute calculations using a % 60. section 4.1.2

Several rules make the behavior precise:

  • Unsigned arithmetic wraps around when its result exceeds the type's range. section 4.1.2
  • Unsigned division and remainder require a nonzero second operand. section 4.1.2
  • Unsigned / and % cannot overflow because their results are no larger than their operands. section 4.1.2
  • Loop code using unsigned indices should handle wraparound explicitly, such as checking the type maximum before incrementing. section 15.0

How Modern C covers it

How deep it goes
Defines reduction modulo SIZE_MAX + 1 and works through boundary examples, but does not develop implementation internals.
Examples
Uses clock arithmetic, minute remainders, SIZE_MAX + 1, 0 - 1, and explicit loop-index checks.
What you can do after
Apply it via C unsigned types while recognizing boundary values and guarding loop increments against unintended wraparound.
How it connects
Connects unsigned wraparound to size_t, overflow, division and remainder, clock arithmetic, and loop indices.

Also explained in

Compare how 3 books explain integer wraparound →

Related concepts

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.