Skip to content

Zig Unreachable

Sometimes you know something the compiler doesn’t: “this number is always between 1 and 7”, or “we can never get here”. Zig lets you write that down with unreachable. If you turn out to be wrong, a debug build stops the program with a clear message instead of carrying on with nonsense. This page covers unreachable, its friend @panic for stopping with your own message, and noreturn, the type of code that never comes back. It’s also the last page of the Control Flow section, so you’ll finish with a small guide to which tool to pick.

unreachable is a promise to the compiler: the program will never get to this line. A common place for it is the else of a switch, when you know the values that can come in:

const std = @import("std");
fn dayName(day: u8) []const u8 {
return switch (day) {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday",
else => unreachable,
};
}
pub fn main() void {
std.debug.print("1 is {s}\n", .{dayName(1)});
std.debug.print("6 is {s}\n", .{dayName(6)});
}

Output:

1 is Monday
6 is Saturday

A u8 can hold 0 to 255, so the switch needs an else. But this program only ever asks for days 1 to 7, so else => unreachable says “any other number would be a bug”. Notice that unreachable fits where the prong needs a []const u8. You’ll see why in the noreturn section below.

Promises get broken. Here the list has a 9 in it, by mistake:

const std = @import("std");
fn dayName(day: u8) []const u8 {
return switch (day) {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday",
else => unreachable,
};
}
pub fn main() void {
const days = [_]u8{ 1, 6, 9 };
for (days) |d| {
std.debug.print("{d} is {s}\n", .{ d, dayName(d) });
}
}

You’ll see something like:

1 is Monday
6 is Saturday
thread 6968 panic: reached unreachable code
main.zig:12:17: 0x11d3119 in dayName (main.zig)
else => unreachable,
^
main.zig:19:54: 0x11d2de9 in main (main.zig)
std.debug.print("{d} is {s}\n", .{ d, dayName(d) });
^

This is a panic: the program stops right away and prints what went wrong, then a stack trace, the list of function calls that led there, newest first. Read it from the top: the panic happened in dayName at line 12, which was called from main at line 19. The thread number and the 0x... addresses change from run to run, and there are usually a few more lines from Zig’s own startup code below these.

So far we’ve used zig run, which makes a debug build. That’s where the safety check above happens. Zig has four build modes, and unreachable behaves differently in them:

Build mode What reaching unreachable does
debug (the default) Panics with reached unreachable code
safe Panics with reached unreachable code
fast Undefined behavior: anything can happen
small Undefined behavior: anything can happen

(Older code and tutorials call them Debug, ReleaseSafe, ReleaseFast and ReleaseSmall: the short names came with Zig 0.17.)

In fast and small, the compiler takes your promise at face value and uses it to make the code faster, for example by not checking the else case at all. If the promise is broken, there’s no safety net. When we ran the example above with zig run -O fast main.zig on our Linux test machine, it printed the first two lines and then crashed with a segmentation fault. On another machine or another Zig version it could print garbage or look like it worked.

If the compiler can work out at compile time that an unreachable is reached, you don’t even get a program. Here dayName(9) is called for a top-level constant, and those are computed while compiling:

const std = @import("std");
fn dayName(day: u8) []const u8 {
return switch (day) {
1 => "Monday",
2 => "Tuesday",
else => unreachable,
};
}
const bad_day = dayName(9);
pub fn main() void {
std.debug.print("{s}\n", .{bad_day});
}
main.zig:7:17: error: reached unreachable code
else => unreachable,
^~~~~~~~~~~
main.zig:11:24: note: called at comptime here
const bad_day = dayName(9);
~~~~~~~^~~

This is part of Zig’s comptime feature, which gets its own lesson in Zig Comptime.

A very common use of unreachable is checking that something is true. The standard library has a helper for it, std.debug.assert, and it’s written as just if (!ok) unreachable;:

const std = @import("std");
fn average(nums: []const u32) u32 {
std.debug.assert(nums.len > 0); // callers must never pass an empty list
var sum: u32 = 0;
for (nums) |n| sum += n;
return sum / @as(u32, @intCast(nums.len));
}
pub fn main() void {
const scores = [_]u32{ 4, 8, 6 };
std.debug.print("average: {d}\n", .{average(&scores)});
}

Output:

average: 6

[]const u32 is a slice, a view of a list of numbers (see Zig Slices), and &scores passes the array as one. @intCast turns the length into a u32 so the division works (see Zig Type Casting). If someone called average with an empty list, a debug build would panic with reached unreachable code right at the assert, instead of dividing by zero further down. Because it’s unreachable underneath, the same build-mode rules apply: the check disappears in fast builds.

unreachable always says the same thing. When you want to stop the program and explain why, use @panic("message"):

const std = @import("std");
fn withdraw(balance: u32, amount: u32) u32 {
if (amount > balance) {
@panic("tried to withdraw more than the balance");
}
return balance - amount;
}
pub fn main() void {
const left = withdraw(100, 30);
std.debug.print("left: {d}\n", .{left});
std.debug.print("left: {d}\n", .{withdraw(left, 500)});
}

You’ll see something like:

left: 70
thread 6984 panic: tried to withdraw more than the balance
main.zig:5:9: 0x11d2fca in withdraw (main.zig)
@panic("tried to withdraw more than the balance");
^
main.zig:13:46: 0x11d2dc8 in main (main.zig)
std.debug.print("left: {d}\n", .{withdraw(left, 500)});
^

There’s one big difference from unreachable: @panic panics in every build mode, fast included. It’s not a promise the optimizer can lean on, it’s an order to stop. So it’s the safer choice when you’re not completely sure something can’t happen. The message is plain text, so to put numbers in it, use std.debug.panic("...{d}...", .{value}), which takes a format string like print.

Some code never finishes in the normal way. unreachable and @panic stop the program. return, break and continue jump somewhere else. A while (true) {} with no break runs forever. All of these have the type noreturn.

The useful thing about noreturn is that it fits in any place a value is expected, because that value will never be needed. That’s why else => unreachable worked in a switch that returns strings, and why you can write this:

const std = @import("std");
fn fail(message: []const u8) noreturn {
std.debug.print("fatal: {s}\n", .{message});
std.process.exit(1);
}
fn toUnsigned(n: i32) u32 {
return if (n >= 0) @intCast(n) else fail("negative input");
}
pub fn main() void {
std.debug.print("{d}\n", .{toUnsigned(42)});
std.debug.print("{d}\n", .{toUnsigned(-5)});
}

Output:

42
fatal: negative input

fn fail(...) noreturn says “calling this never comes back”. It prints a message and calls std.process.exit(1), which ends the program right away with exit code 1 (the number a program hands back to the shell; anything other than 0 means it failed). Since fail is noreturn, it can sit in the else of an if expression that’s supposed to give a u32.

std.process.exit is a calm way to stop: no stack trace, just your message and an exit code. That’s a better fit than a panic for “the user gave us bad input” in a small command-line tool. Note that it ends the program immediately, so defers that haven’t run yet are skipped.

If a function says noreturn but can actually return, Zig won’t compile it:

fn stop() noreturn {
return;
}
pub fn main() void {
stop();
}
main.zig:2:5: error: function declared 'noreturn' returns
return;
^~~~~~
main.zig:1:11: note: 'noreturn' declared here
fn stop() noreturn {
^~~~~~~~

The language reference on noreturn lists everything that has this type.

Situation Use
It can only happen if your code has a bug, and you’re sure unreachable or std.debug.assert
It shouldn’t happen, and you want a message in every build mode @panic("...")
It can happen in normal use (bad input, missing file, network down) An error, see Zig Errors
A command-line tool should stop with a message and an exit code Print, then std.process.exit(1)

When in doubt, prefer an error. Errors let the caller decide what to do, and you’ll see in the next sections of this tutorial that Zig makes them pleasant to work with.

Write fn daysInMonth(month: u8) u8 for a non-leap year: 2 has 28 days; 4, 6, 9 and 11 have 30; 1, 3, 5, 7, 8, 10 and 12 have 31. Use unreachable for anything else. Print the result for months 2, 4 and 12.

Hint: three prongs with lists of values, plus else => unreachable.

Show solution
const std = @import("std");
fn daysInMonth(month: u8) u8 {
return switch (month) {
2 => 28,
4, 6, 9, 11 => 30,
1, 3, 5, 7, 8, 10, 12 => 31,
else => unreachable,
};
}
pub fn main() void {
std.debug.print("month 2: {d}\n", .{daysInMonth(2)});
std.debug.print("month 4: {d}\n", .{daysInMonth(4)});
std.debug.print("month 12: {d}\n", .{daysInMonth(12)});
}

Output:

month 2: 28
month 4: 30
month 12: 31

The else covers the 244 values a u8 can hold that aren’t months. If one of them ever shows up, a debug build panics and shows you where.

Write fn safeDivide(a: u32, b: u32) u32 that divides a by b, but panics with the message division by zero if b is 0. Call it with 20 and 4 and print the answer.

Hint: check b == 0 first and call @panic.

Show solution
const std = @import("std");
fn safeDivide(a: u32, b: u32) u32 {
if (b == 0) @panic("division by zero");
return a / b;
}
pub fn main() void {
std.debug.print("20 / 4 = {d}\n", .{safeDivide(20, 4)});
}

Output:

20 / 4 = 5

Try safeDivide(20, 0) too: the program stops with panic: division by zero and a stack trace. In a real program, dividing by zero might deserve an error instead, so the caller can decide what to do.

Write a noreturn function usage() that prints usage: greet <name> and exits with code 2. Use it in an if expression so the program prints Hello, Ada! when the name isn’t empty and calls usage() when it is.

Hint: const name: []const u8 = if (input.len > 0) input else usage();

Show solution
const std = @import("std");
fn usage() noreturn {
std.debug.print("usage: greet <name>\n", .{});
std.process.exit(2);
}
fn greet(input: []const u8) void {
const name: []const u8 = if (input.len > 0) input else usage();
std.debug.print("Hello, {s}!\n", .{name});
}
pub fn main() void {
greet("Ada");
greet("");
}

Output:

Hello, Ada!
usage: greet <name>

Because usage() is noreturn, it fits in the else of an expression that needs a string. The second call ends the program with exit code 2, so nothing after it runs.

  • unreachable promises the compiler a line can never run. Use it only for things that would be bugs in your own code.
  • In debug and safe builds, reaching it panics with reached unreachable code and a stack trace. In fast and small builds it’s undefined behavior.
  • std.debug.assert(ok) is if (!ok) unreachable;, so the same rules apply.
  • @panic("message") stops the program with your message in every build mode.
  • noreturn is the type of code that never comes back (unreachable, @panic, return, std.process.exit…), and it fits anywhere a value is expected.
  • For things that can go wrong in normal use, use errors, not panics.

Next up: Zig Functions, where you’ll learn to write your own functions with parameters and return values.

Quick check

1. What happens when a debug build reaches unreachable?
2. You need to stop the program with a message even in a -O fast build. What do you use?
3. Why can else => unreachable appear in a switch whose prongs give strings?
4. A user typed a negative number where you need a positive one. What is the best tool?