Skip to content

Zig Integer Overflow

Every integer type has a limit. A u8 stops at 255, a u32 at about four billion. Overflow is what happens when a calculation goes past that limit, like 255 + 1 in a u8. In C this is a famous source of bugs and security holes, because the program usually just carries on with a wrong number. Zig takes a different approach: by default, overflow is treated as a bug, and Zig does its best to catch it. This page shows what that looks like, how build modes change it, and the tools you use when going past the limit is something you expect.

If the compiler can see the overflow, your program doesn’t build:

const std = @import("std");
pub fn main() void {
const max: u8 = 255;
const next = max + 1;
std.debug.print("{d}\n", .{next});
}
main.zig:5:22: error: overflow of integer type 'u8' with value '256'
const next = max + 1;
~~~~^~~

Both values are known at compile time, so the compiler does the math, sees 256 can’t fit in a u8, and stops. This is the best case: the bug never reaches a user.

Most of the time the values only exist while the program runs: a score, a count, something from a file. Then the check happens at runtime:

const std = @import("std");
pub fn main() void {
var lives: u8 = 254;
lives += 1;
std.debug.print("lives: {d}\n", .{lives});
lives += 1;
std.debug.print("lives: {d}\n", .{lives});
}

You’ll see something like:

lives: 255
thread 2429 panic: integer overflow
main.zig:7:11: 0x11d2e0d in main (main.zig)
lives += 1;
^

The first += 1 takes lives to 255, which is fine. The second would make it 256, so Zig stops the program with a panic: it prints what went wrong (integer overflow), the exact file, line and column, and a stack trace showing how the program got there. The thread number and addresses differ on every run, and a few more stack lines follow; we’ve trimmed them here.

A crash sounds bad, but compare it to the alternative: in C, lives would quietly become 0 and the game would carry on with a player who’s suddenly dead. A crash with a line number is a bug you can find in a minute.

Whether that runtime check exists depends on the build mode (Zig calls it the optimization mode). zig run and zig build use debug unless you ask for something else. You pick a mode with -O:

Terminal window
zig run main.zig # debug (the default)
zig run -O safe main.zig
zig run -O fast main.zig
zig run -O small main.zig
Mode Optimized? Overflow at runtime
debug No Panic with a message and stack trace
safe Yes Panic with a message and stack trace
fast Yes, for speed Not checked: illegal behavior
small Yes, for size Not checked: illegal behavior

Before Zig 0.17 these were called Debug, ReleaseSafe, ReleaseFast and ReleaseSmall, and you’ll still see those names in older code. Zig 0.17.1 accepts both spellings.

In fast and small the checks are removed to make the program faster or smaller. Then an overflow is what Zig calls illegal behavior: the compiler assumes it never happens and optimizes based on that, so anything can result. Running the program above with -O fast on our test machine:

Terminal window
zig run -O fast main.zig

You’ll see something like:

lives: 255
lives: 0

Here it happened to wrap around to 0, but nothing promises that. A different Zig version, CPU or surrounding code could give a different result. C programmers know this as “undefined behavior”. The reference explains it in its section on illegal behavior, and the four modes are compared under optimization mode.

The most common overflow: going below zero

Section titled “The most common overflow: going below zero”

You’ll hit overflow with unsigned types far more often than at the top end. An unsigned number can’t go below 0, so subtracting too much overflows too:

const std = @import("std");
pub fn main() void {
var stock: u32 = 0;
stock -= 1;
std.debug.print("stock: {d}\n", .{stock});
}

You’ll see something like:

thread 2785 panic: integer overflow
main.zig:5:11: 0x11d2dc9 in main (main.zig)
stock -= 1;
^

The same thing happens with list.len - 1 when the list is empty. If a value can go negative, use a signed type (i32, i64), or check before you subtract.

The simplest fix is often a type with more room. If a score can go past 255, a u8 was the wrong choice:

const std = @import("std");
pub fn main() void {
var score: u32 = 250;
score += 10;
std.debug.print("score: {d}\n", .{score});
}

Output:

score: 260

When you’re not sure how big a number can get, choose generously: u32, u64 or i64. Saving three bytes is rarely worth a crash.

When there’s a real limit, check it yourself and decide what should happen:

const std = @import("std");
pub fn main() void {
var stock: u32 = 2;
const ordered: u32 = 5;
if (ordered > stock) {
std.debug.print("only {d} left, can't sell {d}\n", .{ stock, ordered });
} else {
stock -= ordered;
std.debug.print("sold {d}, {d} left\n", .{ ordered, stock });
}
}

Output:

only 2 left, can't sell 5

This is often the right answer for business rules, because “not enough stock” is something the user should hear about, not a crash.

If going past the limit is expected, say how it should behave with the operators from Zig Operators:

const std = @import("std");
pub fn main() void {
var frame: u8 = 254;
frame +%= 3; // wraps around: 254, 255, 0, 1
var volume: u8 = 250;
volume +|= 10; // stops at the top
var health: u8 = 4;
health -|= 10; // stops at the bottom
std.debug.print("frame {d}, volume {d}, health {d}\n", .{ frame, volume, health });
}

Output:

frame 1, volume 255, health 0

+%, -% and *% wrap: after the maximum comes zero. That’s guaranteed in every build mode, so it’s safe for hashes, checksums and counters meant to roll over. +|, -| and *| saturate: they stick at the limit, which suits volumes, health bars and colors.

Sometimes you want to know if overflow happened and then decide. @addWithOverflow gives you two things: the wrapped result, and a bit that’s 1 if it overflowed:

const std = @import("std");
pub fn main() void {
var balance: u8 = 250;
balance += 0; // keep it a runtime value
const result, const overflowed = @addWithOverflow(balance, 10);
if (overflowed == 1) {
std.debug.print("overflow! wrapped result would be {d}\n", .{result});
} else {
std.debug.print("new balance: {d}\n", .{result});
}
}

Output:

overflow! wrapped result would be 4

const result, const overflowed = ... unpacks the two values at once (it’s called destructuring). overflowed is a u1, a one-bit number that’s 0 or 1. There’s also @subWithOverflow, @mulWithOverflow and @shlWithOverflow. The reference lists them under builtin overflow functions.

The standard library has math functions that return an error instead of panicking. std.math.add(T, a, b) gives you the sum, or error.Overflow:

const std = @import("std");
pub fn main() void {
var seats: u8 = 250;
seats += 0; // keep it a runtime value
const total = std.math.add(u8, seats, 10) catch {
std.debug.print("too many people for one room\n", .{});
return;
};
std.debug.print("total: {d}\n", .{total});
}

Output:

too many people for one room

catch { ... } runs its block when the call fails, and return leaves main. You’ll learn about errors properly in Zig Errors and Zig Try & Catch. The point here is that overflow becomes a normal error your code can handle and pass up, which fits nicely in functions that already return errors. std.math.sub and std.math.mul work the same way.

For conversions, std.math.cast(u8, x) does the same job as @intCast, but gives you null instead of a panic when the value doesn’t fit:

const std = @import("std");
pub fn main() void {
var big: u32 = 300;
big += 0; // keep it a runtime value
if (std.math.cast(u8, big)) |small| {
std.debug.print("fits: {d}\n", .{small});
} else {
std.debug.print("{d} doesn't fit in a u8\n", .{big});
}
}

Output:

300 doesn't fit in a u8

The |small| part catches the value when there is one. This is how optionals work, covered in Zig Optionals.

A game counts total points with var points: u8 = 200; and adds 100 at the end of a level. That would overflow. Fix it so it prints points: 300.

Hint: the number just needs more room.

Show solution
const std = @import("std");
pub fn main() void {
var points: u16 = 200;
points += 100;
std.debug.print("points: {d}\n", .{points});
}

Output:

points: 300

Points can grow past 255, so u8 was too small. A u16 holds up to 65535; a u32 would be an even safer choice for a total.

Start with var battery: u8 = 5; and drain it by 8. It should stop at 0, not crash. Print battery: 0%.

Hint: saturating subtraction stops at the bottom of the type.

Show solution
const std = @import("std");
pub fn main() void {
var battery: u8 = 5;
battery -|= 8;
std.debug.print("battery: {d}%\n", .{battery});
}

Output:

battery: 0%

-|= subtracts but sticks at 0. A plain -= would panic in a debug build, because a u8 can’t go below zero.

Multiply var width: u16 = 300; by 300 with @mulWithOverflow. If it overflowed, print too big for a u16; otherwise print the area. Keep width runtime with width += 0;.

Hint: const area, const overflowed = @mulWithOverflow(width, 300);

Show solution
const std = @import("std");
pub fn main() void {
var width: u16 = 300;
width += 0;
const area, const overflowed = @mulWithOverflow(width, 300);
if (overflowed == 1) {
std.debug.print("too big for a u16\n", .{});
} else {
std.debug.print("area: {d}\n", .{area});
}
}

Output:

too big for a u16

300 * 300 is 90,000, but a u16 stops at 65,535. @mulWithOverflow tells you instead of panicking, so you choose what to do.

  • Overflow is a result past a type’s limit, like 255 + 1 in a u8. Zig treats it as a bug by default.
  • If the compiler can see it, it’s a compile error. At runtime, debug and safe builds panic with integer overflow and the line number.
  • In fast and small builds there’s no check: overflow is illegal behavior and the result can be anything.
  • Going below zero with unsigned types is the most common case. Use a signed type or check first.
  • Safe options: a bigger type, a check, +% to wrap, +| to saturate, @addWithOverflow, or std.math.add for an error.
  • std.math.cast converts without panicking: it gives null when the value doesn’t fit.

Next up: Zig If…Else, making decisions in your code, and using if to give back a value.

Quick check

1. A runtime var x: u8 = 255; then x += 1; in a debug build. What happens?
2. What happens to the same overflow in a -O fast build?
3. Which line wraps around on purpose, in every build mode?
4. What does @addWithOverflow(a, b) give you?