unreachable

In Debug and ReleaseSafe mode unreachable emits a call to panic with the message reached unreachable code.

In ReleaseFast and ReleaseSmall mode, the optimizer uses the assumption that unreachable code will never be hit to perform optimizations.

Basics

test_unreachable.zig

  1. // unreachable is used to assert that control flow will never reach 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. }

Shell

  1. $ zig test test_unreachable.zig
  2. 1/1 test.basic math... OK
  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. }

Shell

  1. $ zig test test.zig
  2. 1/1 test.this will fail... thread 3574948 panic: reached unreachable code
  3. docgen_tmp/test.zig:3:14: 0x21158c in assert (test)
  4. if (!ok) unreachable; // assertion failure
  5. ^
  6. docgen_tmp/test.zig:8:11: 0x21154a in test.this will fail (test)
  7. assert(false);
  8. ^
  9. /home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/test_runner.zig:63:28: 0x212d23 in main (test)
  10. } else test_fn.func();
  11. ^
  12. /home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:604:22: 0x211eac in posixCallMainAndExit (test)
  13. root.main();
  14. ^
  15. /home/ci/release-0.10.1/out/zig-x86_64-linux-musl-baseline/lib/zig/std/start.zig:376:5: 0x2119b1 in _start (test)
  16. @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{});
  17. ^
  18. error: the following test command crashed:
  19. /home/ci/release-0.10.1/out/zig-local-cache/o/886dbde2c2a21074c6c6d3ff9b83336b/test

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 to compile because
  6. // unreachable expressions are compile errors.
  7. assert(@TypeOf(unreachable) == noreturn);
  8. }
  9. }

Shell

  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:10:24: note: control flow is diverted here
  6. assert(@TypeOf(unreachable) == noreturn);
  7. ^~~~~~~~~~~

See also: