TExcelTAD
Home › Zig › Zig Labeled Blocks & Loops

Zig Labeled Blocks & Loops

A label is a name you attach to a block or loop, written as name: before it. Labels let you do two things that would otherwise need extra variables or goto: produce a value from a block, and break out of (or continue) an outer loop from inside an inner one.

Blocks as expressions

A plain block { … } groups statements but has no value. Give it a label, and break :label value exits the block with a result:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const width: u32 = 12;
    const height: u32 = 5;

    const area = blk: {
        const w = width + 2; // one unit of border on each side
        const h = height + 2;
        break :blk w * h;
    };

    std.debug.print("area with border: {d}\n", .{area});
}
area with border: 98

The helper constants w and h exist only inside the block, so they do not clutter the rest of the function. blk is the conventional name for such a label, but any name works.

This is especially handy for initialising a constant with logic that needs several steps:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const squares = blk: {
        var result: [6]u32 = undefined;
        for (&result, 0..) |*slot, i| {
            const n: u32 = @intCast(i + 1);
            slot.* = n * n;
        }
        break :blk result;
    };
    std.debug.print("{any}\n", .{squares});
}
{ 1, 4, 9, 16, 25, 36 }

squares is a const, even though building it needed a mutable variable — the mutation is sealed inside the block.

Labeled switch branches

Inside a switch, a branch that needs several statements to compute its value uses the same pattern:

zig
const fee = switch (kind) {
    .student => 0,
    .regular => blk: {
        const base = 20;
        break :blk if (is_weekend) base + 5 else base;
    },
};

Breaking out of nested loops

A plain break only leaves the innermost loop. With labels, you choose which loop to leave or continue:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const grid = [_][4]u8{
        .{ 1, 2, 3, 4 },
        .{ 5, 6, 7, 8 },
        .{ 9, 10, 11, 12 },
    };
    const target: u8 = 7;

    var found_row: usize = 0;
    var found_col: usize = 0;
    outer: for (grid, 0..) |row, r| {
        for (row, 0..) |value, c| {
            if (value == target) {
                found_row = r;
                found_col = c;
                break :outer;
            }
        }
    }
    std.debug.print("{d} is at row {d}, column {d}\n", .{ target, found_row, found_col });
}
7 is at row 1, column 2

continue :outer similarly skips the rest of the inner loop and moves on to the next outer iteration:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const words = [_][]const u8{ "sky", "apple", "rhythm", "zig" };
    std.debug.print("words with a vowel:", .{});
    next_word: for (words) |word| {
        for (word) |c| {
            switch (c) {
                'a', 'e', 'i', 'o', 'u' => {
                    std.debug.print(" {s}", .{word});
                    continue :next_word;
                },
                else => {},
            }
        }
    }
    std.debug.print("\n", .{});
}
words with a vowel: apple zig

Labeled loops that produce values

Loops are expressions too. break :label value can return a result from an outer loop, and the loop's else provides the value when nothing was found:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const target: u32 = 24;
    // first factor pair (a, b) with a >= 4 and a * b == target
    const pair = search: for (1..10) |a| {
        for (a..25) |b| {
            if (a * b == target and a >= 4) break :search .{ a, b };
        }
    } else .{ 0, 0 };
    std.debug.print("{d} x {d} = {d}\n", .{ pair[0], pair[1], target });
}
4 x 6 = 24

Summary

Code Effect
name: { … break :name v; } block that evaluates to v
name: for/while … label a loop
break :name leave the labeled loop
continue :name next iteration of the labeled loop
break :name v leave the labeled loop with value v

Tip: Reach for a labeled block whenever you are tempted to write a tiny helper function that is used exactly once.

Test yourself

What does const x = blk: { break :blk 5; }; set x to?

  1. Nothing, it is an error
  2. 5
  3. blk
  4. void

Inside two nested loops, how do you exit both at once?

  1. break break
  2. Label the outer loop and use break :label
  3. return
  4. goto end

What does continue :outer do from inside an inner loop?

  1. Continues the inner loop
  2. Ends the program
  3. Jumps to the next iteration of the outer loop
  4. Restarts the inner loop