if and switch in Zig
Both branch forms produce values, and switch must account for every case.
const std = @import("std");
pub fn main() void {
const wind_knots: u32 = 26;
// if is an expression: both arms produce the value.
const call = if (wind_knots > 33) "stay in harbor" else "reef and go";
std.debug.print("{s}\n", .{call});
// switch must cover every case; ranges use three dots.
const cloud_eighths: u8 = 3;
switch (cloud_eighths) {
0...2 => std.debug.print("clear enough to sail\n", .{}),
3...5 => std.debug.print("broken cloud, watch it\n", .{}),
else => std.debug.print("overcast, compass out\n", .{}),
}
}
How it works
const call = if (...) ... else ...uses if as an expression.switchranges use0...2with three dots, inclusive on both ends.- Leave a case uncovered and the compiler rejects the switch outright —
elsecloses the gap.
Keywords and builtins used here
constelsefnifpubswitchu32u8void
The run, in numbers
- Lines
- 17
- Characters to type
- 525
- Tokens
- 139
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 119 seconds.
Step 1 of 3 in Control flow, step 4 of 27 in Language basics.