OSZig.004: Zig Loops, Ranges, Break, and Continue

Cinematic anime-style young woman programmer at a neon-lit server room workstation, viewing abstract nested loop arrows on a monitor

OSZig.004 teaches repetition in the Zig programming language. A while loop repeats work until its condition becomes false, while for iterates through arrays, slices and bounded integer ranges. Zig also supports break, continue, labels and loops that return values. These capabilities matter when analyzing records, processing device inventories or stopping a search once a match is found. The lesson follows OSZig.003 on if, switch and optionals and uses the official Zig 0.17.1 language reference, released November 3, 2026.

Pokelego Dev, “Loops in Zig,” published May 30, 2026. The presentation covers while, for, continue, break and loops as expressions. Video identity verified from its public listing; actual playback still needs browser testing.

While repeats until a condition changes

A while loop checks its condition before every pass. Its syntax can include a continue expression after a colon, such as : (i += 1), which updates a counter after each completed iteration or after continue. The official reference demonstrates the same construct in the 0.17.1 test examples. Start with a bounded sum, using numbers zero through four:

const std = @import("std");

test "while counts five passes" {
    var i: usize = 0;
    var sum: usize = 0;
    while (i < 5) : (i += 1) {
        sum += i;
    }
    try std.testing.expectEqual(@as(usize, 10), sum);
}

The expected sum is 0 + 1 + 2 + 3 + 4 = 10. The variable i reaches five, the condition becomes false, and the loop ends. Without an increment or another terminating action, a condition can remain true indefinitely. A service must bound iterations and account for cancellation, timeouts and failed inputs.

For traverses arrays and half-open ranges

The for construct captures a value from an array or slice on each pass. The range 0..5 visits zero through four, excluding five. Adding 0.. as a second iterable provides a zero-based index when another bounded collection determines the number of iterations. A bare for (0..) has no bound and is invalid. The official for reference includes indexing, slicing and multiple iterable examples.

test "for ranges and indexed arrays" {
    var count: usize = 0;
    for (0..5) |index| {
        count += index;
    }
    try std.testing.expectEqual(@as(usize, 10), count);

    const readings = [_]u8{ 10, 20, 30 };
    var index_sum: usize = 0;
    for (readings, 0..) |reading, index| {
        _ = reading;
        index_sum += index;
    }
    try std.testing.expectEqual(@as(usize, 3), index_sum);
}

Each captured array element can be used directly; an index is only required when its position matters. The final assertion checks 0 + 1 + 2 = 3. Bounded loops eliminate manually maintained counters for many collection operations. For comparison, OSGo.006 on arrays and slices covers similar iteration concepts in another compiled language.

LEASY, “Discovering Zig Programming Language: Loops,” April 5, 2025. Sections cover while, continue, break, for and infinite loops. The authoritative 0.17.1 documentation controls any version-specific differences; playback remains unverified.

Continue skips; break stops

continue ends the current loop pass and advances to the next one. break ends the loop altogether. Filtering fictional device readings demonstrates both operations. A negative value is skipped, while a sentinel value of 99 stops further processing. Values after the sentinel are never added.

test "continue and break in a for loop" {
    const samples = [_]i32{ 4, -1, 5, 99, 20 };
    var sum: i32 = 0;
    for (samples) |value| {
        if (value < 0) continue;
        if (value == 99) break;
        sum += value;
    }
    try std.testing.expectEqual(@as(i32, 9), sum);
}

The expected result is nine, from four plus five. The examples are educational placeholders; a real monitoring system must not treat an arbitrary integer as a safe shutdown threshold. Inspect OSSQL.006 on missing matches for another illustration of why ignoring or terminating on an input changes downstream results.

A loop can return a value

Zig loops are expressions. A for loop’s else arm runs when the loop finishes normally, without break. A break with an operand can supply a different result. The following function searches a fixed list and returns the first value greater than ten; otherwise it returns zero. Both outcomes are explicitly defined.

fn firstLarge(values: []const i32) i32 {
    return for (values) |value| {
        if (value > 10) break value;
    } else 0;
}

test "for else returns a search result" {
    const small = [_]i32{ 3, 5, 8 };
    const mixed = [_]i32{ 4, 12, 20 };
    try std.testing.expectEqual(@as(i32, 0), firstLarge(&small));
    try std.testing.expectEqual(@as(i32, 12), firstLarge(&mixed));
}

The else expression is not evaluated after a break. Do not confuse the result with an implicit Boolean. In production, zero might be a legitimate match, so an optional return type such as ?i32 could represent absence more accurately, a distinction introduced in OSZig.003.

Labels control nested loops

In nested loops, a plain break leaves only the innermost loop. A labeled form such as break :outer can exit a named outer loop. continue :outer advances a specified outer loop instead. Both forms are shown in the Zig 0.17.1 reference and can simplify a two-dimensional search without extra state variables.

test "labeled break exits the outer loop" {
    var visits: usize = 0;
    outer: for (0..5) |_| {
        for (0..5) |_| {
            visits += 1;
            break :outer;
        }
    }
    try std.testing.expectEqual(@as(usize, 1), visits);
}

With five possible outer and five inner passes, a full traversal could visit 25 pairs. The labeled exit stops after the first pair, leaving visits equal to one. Labels are especially useful when a successful search can terminate several nested loops immediately. They should remain descriptive, and excessive nesting is still a readability warning.

JetBrains interview with Zig creator Andrew Kelley, published May 27, 2026. The discussion adds current context on the language, ecosystem and engineering goals; it is not a substitute for official loop semantics. Video playback has not been independently tested.

Run the tests and review the limitations

Copy all five test blocks and the firstLarge function into one UTF-8 file named loops.zig. Keep the initial const std = @import("std"); declaration once at the top. With Zig 0.17.1 installed from the official download page, run zig test loops.zig and compare the actual test report against the stated expected values. A missing compiler, an incompatible version or a compile error must be reported as a failed or unperformed run, never as a pass.

Exercises: change the first loop bound from five to six and recalculate the expected sum; change the break sentinel from 99 to another test-only value; replace the labeled break with an ordinary break and predict the visit count. Repeated operations are also relevant to OSEmojicode.004 on loops and ranges, despite very different syntax.

Takeaway: Use while for condition-controlled repetition, for for bounded iteration, continue to skip a pass, and break to stop. Loop expressions and labels enable precise control without fabricated output or hidden state.

Editor’s Note: Official Zig 0.17.1 documentation was consulted for loop syntax and expected results. Five Zig test blocks were manually checked against examples in the language reference; they were not executed in a compiler in the editorial environment. Three public YouTube presentations were identified through their listings, but actual playback and mobile rendering require separate checks. The featured 1200 × 630 cinematic-anime cover is original conceptual editorial art, not a runtime screenshot.

Original BitcoinVersus.Tech QR for an optional 5,000-satoshi Bitcoin donation
Original BitcoinVersus.Tech donation QR for an optional 5,000 sats. Verify the recipient and amount independently.

BitcoinVersus.Tech is volunteer-run and publishes independent technical education. An optional 5,000-satoshi donation supports research. Scan the original QR with a compatible Bitcoin wallet or use a wallet able to import a saved QR image. Independently verify recipient 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb and amount before sending. Bitcoin transfers are generally irreversible.

We volunteer daily to ensure the credibility of information on BitcoinVersus.Tech is Verifiably True. The lesson is educational and informational, not authorization to control production equipment, professional engineering advice, financial advice or investment advice.

Leave a Reply