liveBook · Manning

Break statement

As explained in Systems Programming with Zig

break is a control-flow construct that exits a loop or labeled block, optionally producing a value.

Use `break` to leave a loop or a labeled block; either can produce a value. Labels also distinguish exits from nested blocks. section 4.1.3

Listing 4.1 Counting the dictionary words
fn countWordlist(text: []const u8) usize {
    var count: usize = 0;
    var word_iter = std.mem.tokenizeScalar(u8, text, '\n'); #1
    while (word_iter.next()) |_| { #2
        count += 1;
    }

    return count;
}

A labeled block returns either 0 or 1, with deferred resource cleanup kept in the block’s scope. section 4.1.3

Listing 4.2 Comptime type parameters for fun and profit
pub fn tokenizeScalar(
    comptime T: type, #1
    buffer: []const T, #2
    delimiter: T, #3
) TokenIterator(T, .scalar) #4

A labeled block raises the compile-time branch quota, then exits with the parsed embedded wordlist. section 4.1.3

How Systems Programming with Zig covers it

How deep it goes
Explains label syntax and value-producing exits for loops and labeled blocks, including labels for nested blocks.
Examples
Demonstrates conditional resource cleanup and a compile-time wordlist parser that exits with its parsed result.
What you can do after
Apply it via Zig labeled blocks to return a value early while keeping cleanup in scope.
How it connects
Connects labeled blocks with compile-time parsing and resource cleanup using `defer`.

Also explained in

Compare how 8 books explain break statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.