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 basic math...OK
  3. All tests passed.

In fact, this is how assert is implemented:

test.zig

  1. fn assert(ok: bool) void {
  2. if (!ok) unreachable; // assertion failure
  3. }
  4. // This test will fail because we hit unreachable.
  5. test "this will fail" {
  6. assert(false);
  7. }
  1. $ zig test test.zig
  2. Test 1/1 this will fail...reached unreachable code
  3. /home/andy/dev/zig/docgen_tmp/test.zig:2:14: 0x20424c in ??? (test)
  4. if (!ok) unreachable; // assertion failure
  5. ^
  6. /home/andy/dev/zig/docgen_tmp/test.zig:7:11: 0x2040cb in ??? (test)
  7. assert(false);
  8. ^
  9. /home/andy/dev/zig/build/lib/zig/std/special/test_runner.zig:13:25: 0x225beb in ??? (test)
  10. if (test_fn.func()) |_| {
  11. ^
  12. /home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:122:22: 0x225376 in ??? (test)
  13. root.main() catch |err| {
  14. ^
  15. /home/andy/dev/zig/build/lib/zig/std/special/bootstrap.zig:43:5: 0x2250e1 in ??? (test)
  16. @noInlineCall(posixCallMainAndExit);
  17. ^
  18. Tests failed. Use the following command to reproduce the failure:
  19. /home/andy/dev/zig/docgen_tmp/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 because
  6. // evaluating unreachable at compile-time is a compile error.
  7. assert(@typeOf(unreachable) == noreturn);
  8. }
  9. }
  1. $ zig test test.zig
  2. /home/andy/dev/zig/docgen_tmp/test.zig:10:16: error: unreachable code
  3. assert(@typeOf(unreachable) == noreturn);
  4. ^

See also: