If / else that return values
In Zig, an if/else block can return a value that’s assigned to a variable or constant. However - it must be used as a simple expression, without {} braces for the block definitions:
if_else_return.zig |
|
const std = @import("std"); const print = std.debug.print; pub fn main() void { const n_age = 18; const s_response = if (n_age < 18) "underage" else "an adult"; print("You are {s}\n", .{s_response}); } |
|
$ zig run if_else_return.zig |
|
You are an adult |
When returning a value from an if/else, it’s very useful for assigning a value based on a condition in a compact way.
In this example, the value assigned to s_response is determined by the condition and remains an immutable constant. Immutable means it can’t be changed, and it’s a good programming practice: in many cases, preventing a value from being modified after assignment helps avoid hard-to-find bugs.