While Loops
const std = @import("std");
const expect = std.testing.expect;
test "basic while" {
var i: u8 = 2;
while (i < 100) {
i *= 2;
}
try expect(i == 128);
}
test "while with a continue expression" {
// The continue expression runs after every iteration, including ones
// ended by `continue`, which is why it is not just the last statement.
var sum: u8 = 0;
var i: u8 = 1;
while (i <= 10) : (i += 1) {
sum += i;
}
try expect(sum == 55);
}
test "break and continue" {
var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
if (i == 2) continue;
sum += i;
}
try expect(sum == 4); // 0 + 1 + 3
}
test "while as an expression with else" {
// `break x` yields a value; `else` runs when the loop ends normally.
var i: u8 = 0;
const found = while (i < 10) : (i += 1) {
if (i * i > 20) break i;
} else 0;
try expect(found == 5);
}The continue expression
while (i <= 10) : (i += 1) { ... }
The : (i += 1) part runs after every iteration, including ones cut short
by continue. That is precisely why it exists rather than just putting the
increment at the end of the body: with continue in the mix, the two are not
equivalent, and the bug that results is easy to miss.
Loops that produce values
break can carry a value, and while can have an else branch that runs when
the loop finishes without breaking:
const found = while (i < 10) : (i += 1) {
if (i * i > 20) break i;
} else 0;
This is the search-with-fallback pattern as a single expression, with no sentinel variable and no way to forget the not-found case.