Zig While Loop
A while loop repeats a block as long as a condition stays true. Zig's while has two extra tricks: a continue expression that runs after every iteration (so it can replace C's three-part for), and captures for looping over optionals and iterators.
Basic while
const std = @import("std");
pub fn main() void {
var countdown: u32 = 5;
while (countdown > 0) {
std.debug.print("{d}... ", .{countdown});
countdown -= 1;
}
std.debug.print("liftoff!\n", .{});
}5... 4... 3... 2... 1... liftoff!
The continue expression
while (cond) : (step) { … } runs step at the end of each iteration — including iterations that end early with continue. This is Zig's version of C's for (i = 0; i < n; i++):
const std = @import("std");
pub fn main() void {
var i: u32 = 1;
while (i <= 10) : (i += 1) {
if (i % 3 != 0) continue; // the step still runs
std.debug.print("{d} ", .{i});
}
std.debug.print("\n", .{});
// two variables, multiple statements in the step
var a: u32 = 0;
var b: u32 = 1;
var n: u32 = 0;
while (n < 10) : ({
const next = a + b;
a = b;
b = next;
n += 1;
}) {
std.debug.print("{d} ", .{a});
}
std.debug.print("\n", .{});
}3 6 9
0 1 1 2 3 5 8 13 21 34
Tip: To keep the loop counter local to the loop, wrap the whole thing in a block:
{ var i: u32 = 0; while (i < n) : (i += 1) { … } }.
break and continue
| Keyword | Effect |
|---|---|
break |
leave the loop immediately |
continue |
skip to the next iteration (running the continue expression first) |
const std = @import("std");
pub fn main() void {
// find the first power of 2 above 1000
var power: u32 = 1;
var steps: u32 = 0;
while (true) {
power *= 2;
steps += 1;
if (power > 1000) break;
}
std.debug.print("2^{d} = {d}\n", .{ steps, power });
}2^10 = 1024
while with else
A while can have an else branch that runs when the condition becomes false — but not when the loop exits via break. Combined with break value, this makes while an expression:
const std = @import("std");
pub fn main() void {
const data = [_]i32{ 4, 8, 15, 16, 23, 42 };
var i: usize = 0;
const first_odd: ?i32 = while (i < data.len) : (i += 1) {
if (@rem(data[i], 2) != 0) break data[i];
} else null;
std.debug.print("first odd: {?d}\n", .{first_odd});
}first odd: 15
Looping over optionals
while (expr) |value| keeps looping as long as expr returns a non-null value, and captures it. This is the standard pattern for iterators in Zig — every call to next() returns the next item, or null when finished:
const std = @import("std");
pub fn main() void {
var words = std.mem.tokenizeScalar(u8, "plan code test ship", ' ');
var count: u32 = 0;
while (words.next()) |word| {
count += 1;
std.debug.print("{d}: {s}\n", .{ count, word });
}
}1: plan
2: code
3: test
4: ship
The same works for error unions: while (reader.next()) |item| { … } else |err| { … } loops until an error occurs.
Summary
| Form | Use |
|---|---|
while (cond) { … } |
repeat while true |
while (cond) : (i += 1) { … } |
counter loops |
while (it.next()) |x| { … } |
iterators / optionals |
const v = while (…) { … break x; } else y; |
search loops that produce a value |
Test yourself
In while (i < 10) : (i += 1), when does i += 1 run?
- Before each iteration
- After each iteration, including ones ended by
continue - Only when
breakis used - Only once
When does the else branch of a while loop run?
- After every iteration
- When the loop ends because the condition became false
- When the loop exits with
break - Never
What ends while (it.next()) |x| { … }?
- it.next() returning null
- x being 0
- An exception
- A timeout