Zig Error: panic: integer overflow
panic: integer overflow is not a compile error. Your program built fine, started running, and then a calculation gave a result that doesn’t fit in its type: 250 + 10 in a u8 (which stops at 255), or 0 - 1 in an unsigned type (which can’t go below 0). In debug builds Zig stops the program right there, with a stack trace pointing at the line. When Zig can see the overflow while compiling, you get a compile error instead, also covered below. For the other errors in this series, see Zig Errors Explained.
The panic message
Section titled “The panic message”const std = @import("std");
pub fn main() void { var x: u8 = 250; x += 10; std.debug.print("{d}\n", .{x});}You’ll see something like:
thread 1693 panic: integer overflowmain.zig:5:7: 0x11e3de5 in main (main.zig) x += 10; ^The first line is the panic. The next lines are the stack trace: the file, line and column, the function (in main), and the code with a caret under the operator that overflowed. The thread number and addresses change every run, and there are a few more trace lines from Zig’s startup code below these, which you can ignore. The program exits with a crash (on Linux, exit code 134).
What it means
Section titled “What it means”Every Zig integer type has a fixed range. A u8 holds 0 to 255, an i8 holds -128 to 127, a u32 holds 0 to about 4.29 billion. When +, -, * or a cast would go past either end, that’s integer overflow. Many languages quietly wrap around (255 + 1 becomes 0) or, in C’s case for signed numbers, leave the result undefined. Zig treats it as a bug and checks for it.
What happens depends on the build mode:
- In
debug(the default forzig runandzig build) andsafe, the program panics, as above. - In
fastandsmall, there’s no check. Overflow is illegal behaviour: the compiler assumes it never happens, and you get whatever result falls out (in a test here,4). Never rely on that.
That’s why it’s worth running your tests in debug builds. The integer overflow section of the language reference lists every operator that’s checked. The Zig Integer Overflow lesson covers the ranges and operators in depth, and Zig Illegal Behavior explains the build modes.
The classic: items.len - 1
Section titled “The classic: items.len - 1”The overflow beginners hit most isn’t a big number. It’s going below zero with an unsigned type:
const std = @import("std");
fn lastIndex(items: []const u32) usize { return items.len - 1;}
pub fn main() void { const empty: []const u32 = &.{}; std.debug.print("{d}\n", .{lastIndex(empty)});}You’ll see something like:
thread 9591 panic: integer overflowmain.zig:4:22: 0x11e50a9 in lastIndex (main.zig) return items.len - 1; ^main.zig:9:41: 0x11e4dda in main (main.zig) std.debug.print("{d}\n", .{lastIndex(empty)}); ^len is a usize, which can’t be negative. For an empty slice, 0 - 1 overflows. Read the trace from the top: the first location is where it happened (lastIndex), the next one is who called it (main).
How to fix it
Section titled “How to fix it”Fix 1: Check before you subtract
Section titled “Fix 1: Check before you subtract”For len - 1 and similar, handle the edge case first. Returning an optional makes “there is no last index” part of the answer:
const std = @import("std");
fn lastIndex(items: []const u32) ?usize { if (items.len == 0) return null; return items.len - 1;}
pub fn main() void { const empty: []const u32 = &.{}; const three = [_]u32{ 7, 8, 9 }; std.debug.print("{?d} {?d}\n", .{ lastIndex(empty), lastIndex(&three) });}Output:
null 2{?d} prints an optional number, or null. A loop like while (i >= 0) : (i -= 1) with an unsigned i has the same problem (and i >= 0 is always true for unsigned types); count up instead, or loop with while (i > 0) { i -= 1; ... }. See Zig Optionals.
Fix 2: Use a bigger type
Section titled “Fix 2: Use a bigger type”If the value can legitimately grow past the range, the type is just too small. A u8 is fine for a byte, not for a total:
const std = @import("std");
pub fn main() void { const prices = [_]u8{ 200, 100, 50 }; var total: u32 = 0; for (prices) |p| total += p; std.debug.print("{d}\n", .{total});}Output:
350Each u8 price turns into a u32 on its own when added to total, because a u32 can hold every u8 value. For counters and sums, u32, u64 or usize are the usual picks.
Fix 3: Handle it as an error
Section titled “Fix 3: Handle it as an error”When the input comes from outside (a user, a file, the network), overflow is a real possibility, not a bug. std.math.add, sub and mul return error.Overflow instead of panicking:
const std = @import("std");
fn addStock(have: u8, more: u8) !u8 { return std.math.add(u8, have, more);}
pub fn main() void { const a = addStock(200, 50) catch 0; std.debug.print("{d}\n", .{a}); if (addStock(250, 10)) |b| { std.debug.print("{d}\n", .{b}); } else |err| { std.debug.print("can't add: {t}\n", .{err}); }}Output:
250can't add: OverflowThe builtin @addWithOverflow(a, b) (and @subWithOverflow, @mulWithOverflow) gives you the wrapped result plus a bit that says whether it overflowed, if you want to check by hand. See Zig Try and Catch.
Fix 4: Wrap or saturate on purpose
Section titled “Fix 4: Wrap or saturate on purpose”Sometimes wrapping is exactly what you want: hash functions, checksums, ring buffer positions. Zig has separate operators for that, so it’s clear in the code:
const std = @import("std");
pub fn main() void { var x: u8 = 250; _ = &x; std.debug.print("{d} {d}\n", .{ x +% 10, x +| 10 });}Output:
4 255+% wraps around (250 + 10 = 260, minus 256 = 4). +| saturates: it stops at the type’s limit, 255. There are -%, *%, -|, *| too. Use them only when that’s the behaviour you mean; for normal maths, the panic is protecting you.
When Zig catches it while compiling
Section titled “When Zig catches it while compiling”If both values are known at compile time, Zig doesn’t wait for the program to run:
const std = @import("std");
pub fn main() void { const a: u8 = 200; const b = a + 100; std.debug.print("{d}\n", .{b});}main.zig:5:17: error: overflow of integer type 'u8' with value '300' const b = a + 100; ~~^~~~~And putting a literal that’s too big into a type gives type 'u8' cannot represent integer value '300'. Same fixes: a bigger type, or a value that fits. (This is also why examples on this page use var with _ = &x;: it stops the compiler from working the answer out in advance, so you can see the runtime behaviour.)
Where you’ll usually see it
Section titled “Where you’ll usually see it”len - 1,i - 1,end - startwithusizewhen the left side can be smaller.- Small types for totals: a
u8ori16holding a sum, a product or a timestamp. - Casts with
@intCastthat don’t fit. That panic has its own wording:integer does not fit in destination type. See Zig Type Casting. - Countdown loops with unsigned counters.
Related errors
Section titled “Related errors”- index out of bounds: the other runtime panic beginners meet first, often right after an off-by-one.
- attempt to use null value: a panic from unwrapping an optional with
.?. - expected type ‘X’, found ‘Y’: Zig refusing to put a big integer type into a smaller one without a cast.
- All Zig error pages: the full list.
Practice
Section titled “Practice”1. Average without overflow
Section titled “1. Average without overflow”This function panics with integer overflow for { 200, 100, 50 }. Fix it so the program prints average: 116, keeping []const u8 as the parameter.
const std = @import("std");
fn average(nums: []const u8) u8 { var sum: u8 = 0; for (nums) |n| sum += n; return sum / @as(u8, @intCast(nums.len));}
pub fn main() void { const nums = [_]u8{ 200, 100, 50 }; std.debug.print("average: {d}\n", .{average(&nums)});}Hint: the sum needs a bigger type than the numbers. The result of the division still fits in a u8.
Show solution
const std = @import("std");
fn average(nums: []const u8) u8 { var sum: u32 = 0; for (nums) |n| sum += n; return @intCast(sum / nums.len);}
pub fn main() void { const nums = [_]u8{ 200, 100, 50 }; std.debug.print("average: {d}\n", .{average(&nums)});}Output:
average: 116The sum (350) doesn’t fit in a u8, but an average of u8 values always does, so @intCast back to u8 is safe. An empty slice would still be a problem: dividing by zero panics too, so a real version would check nums.len first.
panic: integer overflowhappens at runtime: a result didn’t fit its type.debugandsafebuilds panic;fastandsmalldon’t check, so the result is garbage.- The classic cause is
len - 1on an empty list. Check first, or return an optional. - Too small? Use a bigger type. From outside? Use
std.math.addand handleerror.Overflow. - Want wrapping? Say so with
+%, or saturate with+|. - Known at compile time, it’s a compile error:
overflow of integer type.
Next up: index out of bounds, the panic for reading past the end of an array or slice.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Integer overflow in the Zig language reference: which operations are checked.
- Wrapping operations in the Zig language reference:
+%,-%and*%. - Illegal behavior in the Zig language reference: what the safety checks cover in each build mode.
- Zig Integer Overflow: our lesson with every operator and builtin.