while loops in Zig
The while loop with a continue expression, and one that breaks with a value.
const std = @import("std");
pub fn main() void {
// The continue expression after : runs at the end of each pass.
var lap: u32 = 2;
while (lap <= 8) : (lap += 2) {
std.debug.print("sled dog lap {d}\n", .{lap});
}
// break with a value turns the whole loop into an expression.
var n: u32 = 1;
const first_cube = while (n < 100) : (n += 1) {
if (n * n * n > 300) break n;
} else 0;
std.debug.print("first cube past 300: {d}\n", .{first_cube});
}
How it works
while (lap <= 8) : (lap += 2)runs the step after every pass.break nhands a value out of the loop, making the loop an expression.- The
else 0arm covers the case where the loop ends without breaking.
Keywords and builtins used here
breakconstelsefnifpubu32varvoidwhile
The run, in numbers
- Lines
- 16
- Characters to type
- 445
- Tokens
- 118
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 101 seconds.
Step 2 of 3 in Control flow, step 5 of 27 in Language basics.