liveBook · Manning

Integer overflow

As explained in Systems Programming with Zig

Integer overflow occurs when an arithmetic result cannot be represented in the destination integer type's range.

Integer overflow happens when an arithmetic result exceeds the destination type’s range. In Zig, ordinary addition asserts that overflow will not occur; in safe mode, violating that assertion is illegal behavior and can trigger a debug-mode panic. section 2.1.3

Choose an arithmetic operation according to what the program should do when a result exceeds its range:

  • Use +% (or -% and *%) to wrap the result instead of panicking. section 6.5.4
  • Use @addWithOverflow or @subWithOverflow to receive the wrapped result and a u1 flag indicating whether overflow occurred; @mulWithOverflow provides the same approach for multiplication. section 6.5.4

A Fibonacci value too large for i32

A recursive Fibonacci function using ordinary + eventually overflows an i32; n = 47 is given as a test case. Zig can panic and show a stack trace pointing to the addition. Replacing + with +% makes the result wrap instead. section 2.1.3

Table 6.3 More register instructions
Mnemonic Description

7XKK

Add a constant to a register, wrapping on overflow.

8XY0

Set register X to the value of register Y.

8XY1

Set register X to X | Y.

8XY2

Set register X to X & Y.

8XY3

Set register X to X ^ Y.

8XY4

Set register X to X + Y, and register 0 to the value of the overflow bit.

8XY5

Set register X to X - Y, and register 0 to a 1 if the result is negative (subtraction overflow for unsigned values is equivalent to producing a negative number).

The CHIP-8 register instructions show where the choice matters: some additions wrap, while others store an overflow bit in register 0. section 6.5.4

How Systems Programming with Zig covers it

How deep it goes
Distinguishes checked addition from wrapping arithmetic and shows overflow-result tuples and emulator instruction behavior.
Examples
Uses an overflowing i32 Fibonacci calculation and CHIP-8 register and address instructions.
What you can do after
Apply Zig wrapping operators or overflow-reporting builtins when arithmetic must wrap or expose overflow.
How it connects
Connects integer overflow to Zig arithmetic operators, safe-mode checks, and CHIP-8 register instructions.

Also explained in

Compare how 2 books explain integer overflow →

Related concepts

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