Return statements inside comptime blocks

Hi All,

This is my first Zig question :).

I recently came across the following situation

fn bar() i32 {
  comptime {
    // The condition is added to prevent an 'unreachable code' error
    if (true) {
      return 10;
  return 20;

From what I understand, the idea of a comptime block is that everything within it is executed
at compile time. However, this seems to be an exception. The return statement remains and
becomes part of the “runtime” version of the function which would now return 10 always.

My hypothesis is that return statements always refer to the enclosing function and thus
they would always survive (or outlive) the comptime evaluation process.

Is this hypothesis correct ?
Is this an intended behavior ?

Thank you in advance!


1 Like

Yes I believe your hypothesis is correct. When Zig sees a “return” in a comptime block, it will stop analyzing the rest of the function so it’s as if there is no other code after the return.

Note that if you have a return inside a “conditional block” guarded by a comptime expression, the return will also have the same affect.

fn foo() {
    if (comptime std.builtin.os.tag == .windows) {
        return; // this will cause the analyzer to stop analyzing the
                // function if we're compiling for windows

    // if we get here we can assume we are not compiling for windows

That was just an example to show you that a comptime condition will have the same affect.