liveBook · Manning

WrappingAdd

As explained in Systems Programming with Zig

Wrapping addition is integer addition that returns the modulo-width result when the mathematical sum overflows.

Use Zig’s `+%` when integer addition should return the modulo-width result on overflow. Unlike `+`, it makes wrapping explicit. section 6.5.4 section 2.1.3

Choose the overflow behavior deliberately:

  • Ordinary `+` treats overflow as illegal behavior and can panic in debug or safe mode. section 6.5.4 section 2.1.3
  • `@addWithOverflow` and `@subWithOverflow` return the wrapped result and a `u1` flag indicating whether overflow occurred. section 6.5.4
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-instruction table shows 7XKK adding a constant with wraparound, alongside instructions that expose overflow. section 6.5.4

How Systems Programming with Zig covers it

How deep it goes
Defines `+%` against `+` and contrasts overflow-reporting builtins, without detailing their internals.
Examples
Uses overflowing Fibonacci addition and CHIP-8 register and address instructions as examples.
What you can do after
Apply it via Zig’s `+%` operator to implement additions that are expected to wrap.
How it connects
Connects wrapping addition to integer overflow checks, overflow-reporting builtins, and CHIP-8 instructions.

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.