unreachable

In Debug and ReleaseSafe mode, and when using zig test, unreachable emits a call to panic with the message reached unreachable code.

In ReleaseFast mode, the optimizer uses the assumption that unreachable code will never be hit to perform optimizations. However, zig test even in ReleaseFast mode still emits unreachable as calls to panic.

Basics

test.zig

  1. // unreachable is used to assert that control flow will never happen upon a
  2. // particular location:
  3. test "basic math" {
  4. const x = 1;
  5. const y = 2;
  6. if (x + y != 3) {
  7. unreachable;
  8. }
  9. }
  1. $ zig test test.zig
  2. Test [1/1] test "basic math"...
  3. All 1 tests passed.

In fact, this is how std.debug.assert is implemented:

test.zig

  1. // This is how std.debug.assert is implemented
  2. fn assert(ok: bool) void {
  3. if (!ok) unreachable; // assertion failure
  4. }
  5. // This test will fail because we hit unreachable.
  6. test "this will fail" {
  7. assert(false);
  8. }
  1. $ zig test test.zig
  2. Test [1/1] test "this will fail"...
  3. thread 6650 panic: reached unreachable code
  4. /home/andy/Downloads/zig/docgen_tmp/test.zig:3:14: 0x20808b in assert (test)
  5. if (!ok) unreachable; // assertion failure
  6. ^
  7. /home/andy/Downloads/zig/docgen_tmp/test.zig:8:11: 0x20679e in test "this will fail" (test)
  8. assert(false);
  9. ^
  10. /home/andy/Downloads/zig/lib/std/special/test_runner.zig:76:28: 0x22d48a in std.special.main (test)
  11. } else test_fn.func();
  12. ^
  13. /home/andy/Downloads/zig/lib/std/start.zig:458:37: 0x225a6a in std.start.callMain (test)
  14. const result = root.main() catch |err| {
  15. ^
  16. /home/andy/Downloads/zig/lib/std/start.zig:400:12: 0x20955e in std.start.callMainWithArgs (test)
  17. return @call(.{ .modifier = .always_inline }, callMain, .{});
  18. ^
  19. /home/andy/Downloads/zig/lib/std/start.zig:319:17: 0x208565 in std.start.posixCallMainAndExit (test)
  20. std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp }));
  21. ^
  22. /home/andy/Downloads/zig/lib/std/start.zig:244:5: 0x2082c2 in std.start._start (test)
  23. @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
  24. ^
  25. error: the following test command crashed:
  26. docgen_tmp/zig-cache/o/838077344bc971dfe73a08c5661e78d1/test /home/andy/Downloads/zig/build/zig

At Compile-Time

test.zig

  1. const assert = @import("std").debug.assert;
  2. test "type of unreachable" {
  3. comptime {
  4. // The type of unreachable is noreturn.
  5. // However this assertion will still fail because
  6. // evaluating unreachable at compile-time is a compile error.
  7. assert(@TypeOf(unreachable) == noreturn);
  8. }
  9. }
  1. $ zig test test.zig
  2. ./docgen_tmp/test.zig:10:16: error: unreachable code
  3. assert(@TypeOf(unreachable) == noreturn);
  4. ^
  5. ./docgen_tmp/test.zig:3:28: note: referenced here
  6. test "type of unreachable" {
  7. ^

See also: