Blocks

A block is a piece of code surrounded by { and }. Blocks can be used to limit the scope of identifiers:

const std = @import("std");
const print = std.debug.print;

pub fn main() void {
    {
        const a: bool = true;
        print("a is {}\n", .{a});
    }

    {
        // This `a` is independent from the `a` above.
        var a: u64 = 123;
        a *= 2;
        print("a is {}\n", .{a});
    }
}
$ zig run blocks.zig
a is true
a is 246

We can use a block as an expression if we give it a label and use a break with that label to return a value:

const std = @import("std");
const print = std.debug.print;

pub fn main() void {
    const pi_half = blk: {
        const pi = 3.1415;
        break :blk pi / 2.0;
    };
    print("pi/2 ≈ {d:.4}\n", .{pi_half});
}
$ zig run block-expr.zig 
pi/2 ≈ 1.5708

Next example: Defer.