Zig NEWS

Pyrolistical
Pyrolistical

Posted on

Puzzler: pre-defer?

Given,

test {
    defer _ = foo;
    const foo = 6;
}
Enter fullscreen mode Exit fullscreen mode

What happens we run zig test upon it?

  1. Test passes.
  2. Test fails with panic.
  3. Compile error: use of undeclared identifier 'foo'.
  4. Compile error: unused local constant.
  5. None of the above.

The answer is after the giraffe.

giraffe

The answer is C. Compile error: use of undeclared identifier 'foo'.

This makes sense if you consider a block can return before an identifier is declared. This would cause the defer to refer to an non-existent identifier.

test {
  defer std.debug.print("{}", .{ foo });
  if (maybe) {
    // if original test did pass, the defer would be required to print foo here
    return;
  }
  const foo = 6;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)