liveBook · Manning

Numerical overflow

As explained in Modern C

Arithmetic overflow is the condition in which an arithmetic result is outside the range representable by its type.

A result that fits

With `size_t a = 45` and `size_t b = 7`, `(a - b)*2` is 76, while `a - b*2` is 31. Both results fit in `size_t`, so the arithmetic gives the mathematical results. Parentheses change which calculation is performed; they do not change the range the type can represent. section 4.1.1

Numerical overflow occurs when an arithmetic result is outside its type’s representable range. For `size_t`, that range is 0 through `SIZE_MAX`: multiplying two sufficiently large values can produce a mathematical result greater than `SIZE_MAX`. section 4.1.1

TAKEAWAY: Unsigned arithmetic is always well defined, but a `size_t` addition, subtraction, or multiplication gives the mathematical result only when that result is representable. “Well defined” does not mean “always mathematically exact.” section 4.1.1

   for (unsigned i = 1; i; ++i) do_something();
   for (  signed i = 1; i; ++i) do_something();


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":6}],[{\"line\":1,\"ch\":3},{\"line\":1,\"ch\":6}],[{\"line\":0,\"ch\":8},{\"line\":0,\"ch\":16}],[{\"line\":0,\"ch\":3},{\"line\":0,\"ch\":6}],[{\"line\":1,\"ch\":3},{\"line\":1,\"ch\":6}],[{\"line\":0,\"ch\":10},{\"line\":0,\"ch\":16}],[{\"line\":1,\"ch\":10},{\"line\":1,\"ch\":16}]]"}
!@%STYLE%@!

The two loops differ only in whether `i` is unsigned or signed. That distinction matters when reasoning about arithmetic at the type’s range limit; do not transfer an unsigned-arithmetic guarantee to a signed variable. section 5.7.5

Signed integers require separate care: their treatment raises questions about both overflow and sign representation. In performance-sensitive C code, integer overflow is also a safety concern. Do not trade the obligation to check arithmetic assumptions for a clever optimization. section 5.7.5 section 15.0

How Modern C covers it

How deep it goes
Defines overflow using `size_t` and `SIZE_MAX`, then distinguishes signed types without detailing how C handles overflowing results.
Examples
Uses `size_t` arithmetic, a product exceeding `SIZE_MAX`, and paired signed and unsigned loops.
What it assumes
Assumes familiarity with C arithmetic expressions and integer types; introduces the representability limit through `size_t` and `SIZE_MAX`.
What you can do after
Evaluate/understand when integer arithmetic yields an exact result and why type range must be considered before relying on one.
How it connects
Connects overflow to unsigned arithmetic, signed integers, integer representation, and performance-related safety.

Also explained in

Compare how 7 books explain numerical overflow →

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.