Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Control Flow and Functions

Loops

Learn Zig loops: while with continue expressions, for over slices and ranges, indexes, multiple sequences, break with values, labeled loops, else clauses and inline for.

Zig has two loop keywords, while and for, and each one fits a job. while repeats while a condition holds, for visits every element of one or more sequences. Neither has an awkward three-part header: the loop counter lives where you declare it, and the update goes in a continue expression.

while

ZIG
const std = @import("std");

pub fn main() void {
    var i: u32 = 0;
    while (i < 5) {
        std.debug.print("{d} ", .{i});
        i += 1;
    }
    std.debug.print("\n", .{});
}

Output: 0 1 2 3 4 .

The condition is a bool. To keep the update next to the condition (like C's for), add a continue expression after a colon:

ZIG
var i: u32 = 0;
while (i < 5) : (i += 1) {
    std.debug.print("{d} ", .{i});
}

The : (i += 1) part runs after every iteration, including iterations ended with continue, which fixes the classic bug where a continue skips the increment and loops forever.

break and continue

break leaves the loop and continue jumps to the next iteration:

ZIG
var n: u32 = 0;
while (true) : (n += 1) {
    if (n % 2 == 0) continue;     // skip even numbers
    if (n > 9) break;             // stop after 9
    std.debug.print("{d} ", .{n});
}

Output: 1 3 5 7 9 .

while with optionals

When the condition is an optional, the loop runs until it becomes null, binding the unwrapped value each time. This is the standard way to consume iterators:

ZIG
var parts = std.mem.splitScalar(u8, "a,b,c", ',');
while (parts.next()) |part| {
    std.debug.print("[{s}]", .{part});
}

Output: [a][b][c].

Loops are expressions

A while can have an else branch that runs when the loop ends without break, and break can carry a value:

ZIG
const numbers = [_]i32{ 4, 8, 15, 16, 23, 42 };

var index: usize = 0;
const first_odd: ?i32 = while (index < numbers.len) : (index += 1) {
    if (numbers[index] % 2 != 0) break numbers[index];
} else null;
// first_odd == 15

for

for iterates over arrays, slices and ranges, capturing each element between pipes:

ZIG
const std = @import("std");

pub fn main() void {
    const fruits = [_][]const u8{ "apple", "banana", "cherry" };

    for (fruits) |fruit| {
        std.debug.print("{s}\n", .{fruit});
    }
}

Indexes and ranges

Add a second sequence to get an index. 0.. is an open-ended range that counts up:

ZIG
for (fruits, 0..) |fruit, i| {
    std.debug.print("{d}: {s}\n", .{ i, fruit });
}
TEXT
0: apple
1: banana
2: cherry

A range a..b (end excluded) is a sequence of numbers, which replaces the C-style counting loop:

ZIG
for (0..5) |i| {
    std.debug.print("{d} ", .{i});     // 0 1 2 3 4
}

The capture i has type usize. You can loop over several sequences at once if they have the same length; Zig checks this (at compile time when known, otherwise with a runtime panic in safe modes):

ZIG
const names = [_][]const u8{ "Ada", "Linus" };
const years = [_]u16{ 1815, 1969 };
for (names, years) |name, year| {
    std.debug.print("{s} {d}\n", .{ name, year });
}

Mutating elements

Capture by pointer with * to change items in place. The slice must be mutable:

ZIG
var values = [_]i32{ 1, 2, 3 };
for (&values) |*v| {
    v.* *= 10;
}
// values == { 10, 20, 30 }

&values makes a pointer to the array, and *v captures a pointer to each element; v.* reads or writes through it.

Labeled loops

To break out of or continue an outer loop from an inner one, label the loop and name the label:

ZIG
const std = @import("std");

pub fn main() void {
    outer: for (1..5) |a| {
        for (1..5) |b| {
            if (a * b == 6) {
                std.debug.print("found {d} x {d}\n", .{ a, b });
                break :outer;
            }
        }
    }
}

Output: found 2 x 3. continue :outer jumps to the next iteration of the outer loop. Labels replace C's goto for this purpose.

inline for and inline while

inline for unrolls the loop at compile time. It is needed when each iteration has a different type, for example when looping over the fields of a struct. Ordinary loops are enough for everything else; you will meet inline in the comptime chapter.

Common mistakes

  • Infinite while loop: forgetting to change the variable. A continue expression prevents it.
  • Wrong range end: 0..n stops before n; use 0..n + 1 to include it.
  • Mismatched lengths in a multi-sequence for.
  • Modifying a const array through |*v|: the compiler rejects it; declare the array with var.

Stand-ins you can run

Rust's for with ranges, enumerate and zip is the closest match for Zig's multi-sequence loops.

Rust Stand-in (Rust): ranges, indexes, zip, labels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

C needs the manual pattern, and the continue-skips-the-increment bug is real in while loops:

C Stand-in (C): the continue expression, written by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the part after the colon in while (i < 5) : (i += 1) do?

    The continue expression runs at the end of every iteration, including iterations ended by continue.
  2. 2. How do you loop from 0 to 4 in Zig?

    0..5 is a range excluding 5, and the capture goes between pipes.
  3. 3. What does for (items, 0..) |item, i| provide?

    The open range 0.. supplies a counter alongside the items.
  4. 4. How do you exit an outer loop from inside an inner loop?

    Labeled loops let break and continue target a specific loop.
  5. 5. How do you modify the elements of an array in a for loop?

    Capturing with |v| gives a pointer to each element, and v. reads or writes it.

Summary

  • while (cond) : (update) loops with a continue expression; while (opt) |v| consumes optionals until null.
  • for (seq) |item| visits elements; add 0.. for an index, or give several equal-length sequences.
  • for (0..n) replaces counting loops; ranges exclude their end.
  • Capture by pointer (|*v|) to modify elements in place.
  • Labels (outer:) with break :outer and continue :outer control nested loops; loops can break with a value and have else.

Next: Functions