Skip to content

Zig Break/Continue

You’ve already used break and continue in the while and for lessons. This page puts them in one place and adds the part that makes Zig’s version special: labels. With a label you can jump out of two loops at once, which in C usually means a goto or an extra “found” flag. And because Zig loops can produce a value, break can hand that value straight back.

break ends the loop immediately. The program carries on with the first line after the loop:

const std = @import("std");
pub fn main() void {
const orders = [_]u32{ 20, 35, 0, 50 };
for (orders) |amount| {
if (amount == 0) {
std.debug.print("Found an empty order, stopping.\n", .{});
break;
}
std.debug.print("Processing order of {d}\n", .{amount});
}
std.debug.print("Done.\n", .{});
}

Output:

Processing order of 20
Processing order of 35
Found an empty order, stopping.
Done.

The 50 is never processed, because the loop ended at the 0.

continue skips the rest of the current round and goes on with the next item:

const std = @import("std");
pub fn main() void {
const readings = [_]i32{ 12, -1, 15, -1, 9 };
var sum: i32 = 0;
for (readings) |r| {
if (r < 0) continue; // -1 means "sensor offline"
sum += r;
}
std.debug.print("Sum of valid readings: {d}\n", .{sum});
}

Output:

Sum of valid readings: 36

continue is a nice way to handle the “skip this one” cases at the top of a loop, so the main work below doesn’t have to sit inside an extra if. In a while loop with a continue expression, like while (i < n) : (i += 1), continue still runs the i += 1.

A plain break or continue only affects the innermost loop it’s in. Watch what happens when you try to stop a search through a grid:

const std = @import("std");
pub fn main() void {
const grid = [_][3]u8{
.{ 1, 2, 3 },
.{ 4, 5, 6 },
.{ 7, 8, 9 },
};
for (grid, 0..) |row, r| {
for (row) |value| {
std.debug.print("checking row {d}: {d}\n", .{ r, value });
if (value == 5) break;
}
}
}

Output:

checking row 0: 1
checking row 0: 2
checking row 0: 3
checking row 1: 4
checking row 1: 5
checking row 2: 7
checking row 2: 8
checking row 2: 9

[_][3]u8 is an array of rows, each row an array of 3 numbers. We found the 5, but the break only left the inner loop, so the outer loop went on to row 2. In C you’d add a bool found and check it in the outer loop, or reach for goto.

Zig’s answer is a label. You put a name and a colon in front of a loop, like outer:, and then break :outer leaves that loop, no matter how deep you are:

const std = @import("std");
pub fn main() void {
const grid = [_][3]u8{
.{ 1, 2, 3 },
.{ 4, 5, 6 },
.{ 7, 8, 9 },
};
outer: for (grid, 0..) |row, r| {
for (row) |value| {
std.debug.print("checking row {d}: {d}\n", .{ r, value });
if (value == 5) break :outer;
}
}
std.debug.print("search finished\n", .{});
}

Output:

checking row 0: 1
checking row 0: 2
checking row 0: 3
checking row 1: 4
checking row 1: 5
search finished

Now both loops stop at the 5. The label can be any name you like; outer is common because it says which loop you mean. Rust and Java have the same idea (Rust writes 'outer:).

continue :outer skips the rest of the current round of the outer loop and moves on to its next item. That’s useful when you’re done with one row as soon as you find something in it:

const std = @import("std");
pub fn main() void {
const grid = [_][4]i32{
.{ 3, -1, 8, 2 },
.{ 5, 6, 7, 1 },
.{ -4, 2, 0, -9 },
};
rows: for (grid, 0..) |row, r| {
for (row) |value| {
if (value < 0) {
std.debug.print("row {d}: first negative is {d}\n", .{ r, value });
continue :rows;
}
}
std.debug.print("row {d}: no negatives\n", .{r});
}
}

Output:

row 0: first negative is -1
row 1: no negatives
row 2: first negative is -4

In row 0, continue :rows jumps straight to row 1, so the “no negatives” line is skipped. Row 1 has no negatives, so its inner loop ends normally and that line prints.

Labels work the same way on while loops, and you can mix them: a for inside a while, a while inside a for. The language reference on labeled while shows the while version.

In Zig, loops are expressions: they can produce a value. break value ends the loop and makes value its result. The loop’s else branch gives the result when it ends without a break:

const std = @import("std");
pub fn main() void {
const ages = [_]u8{ 12, 15, 19, 22 };
const first_adult: ?u8 = for (ages) |age| {
if (age >= 18) break age;
} else null;
std.debug.print("First adult: {?d}\n", .{first_adult});
}

Output:

First adult: 19

?u8 means “a u8 or null” (more in Zig Optionals), and {?d} prints it. If no age were 18 or over, the else would make the result null, and it would print First adult: null.

The real power comes when you combine a value with a label. break :outer value leaves both loops and gives a result:

const std = @import("std");
pub fn main() void {
const grid = [_][3]u8{
.{ 1, 2, 3 },
.{ 4, 5, 6 },
.{ 7, 8, 9 },
};
const target: u8 = 8;
const row_index: ?usize = outer: for (grid, 0..) |row, r| {
for (row) |value| {
if (value == target) break :outer r;
}
} else null;
if (row_index) |r| {
std.debug.print("{d} is in row {d}\n", .{ target, r });
} else {
std.debug.print("{d} is not in the grid\n", .{target});
}
}

Output:

8 is in row 2

This replaces the whole “flag variable plus break plus check after the loop” dance from C with one expression. The label goes right before the loop, even when the loop sits on the right side of =.

Zig is strict about labels and loop keywords, which saves you from some confusing bugs.

An unused label is an error. If you add a label and never break or continue to it, Zig asks you to remove it:

const std = @import("std");
pub fn main() void {
outer: for (0..3) |i| {
std.debug.print("{d}\n", .{i});
}
}
main.zig:4:5: error: unused for loop label
outer: for (0..3) |i| {
^~~~~

A label must exist. break :outer when there’s no loop called outer around it gives error: label not found: 'outer'.

break and continue need a loop. Using them outside any loop gives error: break expression outside loop or error: continue expression outside loop. (The one exception is a labeled block, where break :label value is how you return a value. That’s the next lesson.)

Find the first number above 50 that divides evenly by 7. Use a for loop over the range 51..100 and break with a value.

Hint: const found: usize = for (51..100) |n| { if (n % 7 == 0) break n; } else 0;

Show solution
const std = @import("std");
pub fn main() void {
const found: usize = for (51..100) |n| {
if (n % 7 == 0) break n;
} else 0;
std.debug.print("First multiple of 7 above 50: {d}\n", .{found});
}

Output:

First multiple of 7 above 50: 56

The loop stops at 56 and that becomes its value. Range values are usize, so found is a usize too.

Count the characters in "a b c d" that aren’t spaces, using continue to skip spaces.

Hint: if (c == ' ') continue;

Show solution
const std = @import("std");
pub fn main() void {
const text = "a b c d";
var count: u32 = 0;
for (text) |c| {
if (c == ' ') continue;
count += 1;
}
std.debug.print("Non-space characters: {d}\n", .{count});
}

Output:

Non-space characters: 4

Each space hits continue, so count += 1 only runs for the four letters.

Find the first two different positions i and j in [_]i32{ 3, 9, 4, 7, 1 } whose numbers add up to 11, and print them. Stop both loops as soon as you find a pair.

Hint: label the outer loop, loop j over i + 1..nums.len in the inner loop, and use break :outer once you’ve printed the pair.

Show solution
const std = @import("std");
pub fn main() void {
const nums = [_]i32{ 3, 9, 4, 7, 1 };
outer: for (nums, 0..) |a, i| {
for (i + 1..nums.len) |j| {
if (a + nums[j] == 11) {
std.debug.print("nums[{d}] + nums[{d}] = {d} + {d} = 11\n", .{ i, j, a, nums[j] });
break :outer;
}
}
}
}

Output:

nums[2] + nums[3] = 4 + 7 = 11

Starting j at i + 1 means you never pair a number with itself or check a pair twice. break :outer stops both loops once the first pair is found.

  • break ends a loop right away; continue skips to the next round.
  • A plain break or continue only affects the innermost loop. Inside a switch, break leaves the loop around it.
  • Put a label in front of a loop (outer: for ...) and use break :outer or continue :outer to reach it from inside nested loops.
  • Loops can produce a value: break value, with an else for when no break happened.
  • break :outer value leaves several loops and returns a result in one step.
  • Unused labels, missing labels and break outside a loop are compile errors.

Next up: Zig Blocks, where labels let a block of code produce a value.

Quick check

1. You have a for inside a for. Where does a plain break in the inner loop go?
2. What does continue :rows do inside an inner loop?
3. What is x after const x: ?u8 = for (items) |v| { if (v > 10) break v; } else null; if no item is over 10?
4. In Zig, a break inside a switch prong that sits in a for loop...