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.zig

  1. fn foo(condition: bool, b: u32) void {
  2. const a = if (condition) b else return;
  3. @panic("do something with a");
  4. }
  5. test "noreturn" {
  6. foo(false, 1);
  7. }
  1. $ zig test test.zig
  2. Test [1/1] test "noreturn"...
  3. All 1 tests passed.

Another use case for noreturn is the exit function:

test.zig

  1. pub extern "kernel32" fn ExitProcess(exit_code: c_uint) callconv(if (@import("builtin").target.cpu.arch == .i386) .Stdcall else .C) noreturn;
  2. test "foo" {
  3. const value = bar() catch ExitProcess(1);
  4. try expect(value == 1234);
  5. }
  6. fn bar() anyerror!u32 {
  7. return 1234;
  8. }
  9. const expect = @import("std").testing.expect;
  1. $ zig test test.zig -target x86_64-windows
  2. warning: created docgen_tmp/zig-cache/o/c42fd17f6f3b779d958fa42345e9399d/test.exe but skipping execution because it is non-native