Zig Break and Continue
Break and continue are statements that change how a loop runs. Break leaves the loop at once, and continue skips ahead to the next run.
Break stops the loop early
The loop could print up to 9, but the if breaks out at 3. The printed lines stop before 3 appears.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
for (0..10) |i| {
if (i == 3) break;
try out.print("{d}\n", .{i});
}
}
Continue skips one run and keeps looping
When i is 2, continue jumps to the next run before the print. Every other number still prints.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
for (0..5) |i| {
if (i == 2) continue;
try out.print("{d}\n", .{i});
}
}
Break stops a search at the first match
The loop hunts for the first number divisible by 7. It prints 7 and breaks, so 14 is never reached.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
for (1..20) |n| {
if (n % 7 == 0) {
try out.print("{d}\n", .{n});
break;
}
}
}
Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
for (1..11) |i| {
if (i % 3 == 0) continue;
if (i == 8) break;
try out.print("{d}\n", .{i});
}
}
Key points
- Break: break exits the loop it sits inside at once.
- Continue: continue ends the current run early and starts the next run of the loop.
- Condition: both statements are usually placed inside an if inside the loop.
- Search: break is useful once a loop has found the value it was looking for.
- Skip: continue is useful for passing over items that need no work.
In this example, the loop walks from 1 upward and skips 3 and 6 because continue fires on multiples of 3. When i reaches 8, break ends the loop, so the printed lines are 1, 2, 4, 5, and 7.
Note
break and continue act on the nearest loop around them.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A loop should skip printing the number 2 but keep printing the numbers after it. Which statement inside an if does that job?