noreturn

noreturn is the type of:

  • break
  • continue
  • return
  • unreachable
  • while (true) {}

When resolving types together, such as if clauses or switch prongs, the noreturn type is compatible with every other type. Consider:

test_noreturn.zig

  1. fn foo(condition: bool, b: u32) void {
  2. const a = if (condition) b else return;
  3. _ = a;
  4. @panic("do something with a");
  5. }
  6. test "noreturn" {
  7. foo(false, 1);
  8. }

Shell

  1. $ zig test test_noreturn.zig
  2. 1/1 test "noreturn"... OK
  3. All 1 tests passed.

Another use case for noreturn is the exit function:

noreturn_from_exit.zig

  1. const std = @import("std");
  2. const builtin = @import("builtin");
  3. const native_arch = builtin.cpu.arch;
  4. const expect = std.testing.expect;
  5. const WINAPI: std.builtin.CallingConvention = if (native_arch == .i386) .Stdcall else .C;
  6. extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(WINAPI) noreturn;
  7. test "foo" {
  8. const value = bar() catch ExitProcess(1);
  9. try expect(value == 1234);
  10. }
  11. fn bar() anyerror!u32 {
  12. return 1234;
  13. }

Shell

  1. $ zig test noreturn_from_exit.zig -target x86_64-windows --test-no-exec