liveBook · Manning

Label

As explained in Systems Programming with Zig

A label is a name attached to a block or loop that permits targeted break control flow.

In Zig, a label names a block so a break can target it and return a value. Start the block with a name and colon, then exit it with `break :name value`. Labels also distinguish nested blocks. section 4.1.3

Listing 4.5 Using labels
const result: i32 = a: {
    const some_resource: Resource = .init();
    defer some_resource.deinit(); #1

    if (some_resource.some_condition()) {
        break :a 0;
    }
    break :a 1;
};

The block returns either 0 or 1 while keeping the resource and its deferred cleanup in a local scope. section 4.1.3

Listing 4.6 Using our parser
const words = blk: { #1
    @setEvalBranchQuota(1_000_000); #2
    break :blk parseWordlist(@embedFile("words.txt")); #3
};

A labeled block sets the compile-time branch quota, then returns the parsed contents of an embedded wordlist. section 4.1.3

How Systems Programming with Zig covers it

How deep it goes
Explains label syntax, targeted breaks, returned values, and differentiation of nested blocks.
Examples
Demonstrates scoped resource cleanup and parsing an embedded wordlist.
What you can do after
Practice naming blocks and returning values with targeted breaks.
How it connects
Connects labels to break, scope, defer, and compile-time evaluation.

Also explained in

Compare how 4 books explain label →

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.