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.
Caught by the compiler
Section titled “Caught by the compiler”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.
Caught at runtime: a panic
Section titled “Caught at runtime: a panic”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: 255thread 2429 panic: integer overflowmain.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.
Build modes change the rules
Section titled “Build modes change the rules”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:
zig run main.zig # debug (the default)zig run -O safe main.zigzig run -O fast main.zigzig 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:
zig run -O fast main.zigYou’ll see something like:
lives: 255lives: 0Here 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 overflowmain.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.
Option 1: use a bigger type
Section titled “Option 1: use a bigger type”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: 260When you’re not sure how big a number can get, choose generously: u32, u64 or i64. Saving three bytes is rarely worth a crash.
Option 2: check before you change
Section titled “Option 2: check before you change”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 5This is often the right answer for business rules, because “not enough stock” is something the user should hear about, not a crash.
Option 3: wrap or saturate on purpose
Section titled “Option 3: wrap or saturate on purpose”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.
Option 4: find out whether it overflowed
Section titled “Option 4: find out whether it overflowed”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 4const 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.
Option 5: get an error with std.math
Section titled “Option 5: get an error with std.math”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 roomcatch { ... } 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 u8The |small| part catches the value when there is one. This is how optionals work, covered in Zig Optionals.
Practice
Section titled “Practice”1. Pick the right fix
Section titled “1. Pick the right fix”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: 300Points 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.
2. A battery that can’t go below zero
Section titled “2. A battery that can’t go below zero”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.
3. Report the overflow
Section titled “3. Report the overflow”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 u16300 * 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 + 1in au8. 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 overflowand 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, orstd.math.addfor an error. std.math.castconverts without panicking: it givesnullwhen 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Integer Overflow: default operations,
std.mathfunctions, overflow builtins and wrapping. - Zig language reference: Illegal Behavior: what checked and unchecked illegal behavior mean.
- Zig language reference: Optimization Mode:
debug,safe,fastandsmallcompared. - Zig language reference: @setRuntimeSafety: turning safety checks on or off for one block.