Lesson contents

Break statement

End the loop as soon as the stopping condition is true. Later numbers are never visited.

Simple example

Stop before three.

Start1 → 4 · stop at 3
Result1 2
lesson.zig
const std = @import("std");

pub fn main() !void {
    for (1..4 + 1) |number| {
        if (number == 3) {
            break;
        }
        std.debug.print("{any}\n", .{number});
    }
}
Output
1
2
Advertisements

Everyday examples

A gate closes before ticket 13. Which tickets from 11 through 15 enter?

Start11 → 15 · stop at 13
Result11 12
lesson.zig
const std = @import("std");

pub fn main() !void {
    for (11..15 + 1) |ticket| {
        if (ticket == 13) {
            break;
        }
        std.debug.print("{any}\n", .{ticket});
    }
}
Output
11
12
Run the example
Terminal
zig run lesson.zig
Official documentation