TExcelTAD
Home › Zig › Zig For Loop

Zig For Loop

Zig's for loop is not C's counter loop. It walks over the elements of arrays, slices and ranges — and it can walk over several of them at once, in lockstep. For "repeat while a condition holds" use while; for "do something with each item" use for.

Looping over a collection

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const fruits = [_][]const u8{ "mango", "lychee", "durian" };
    for (fruits) |fruit| {
        std.debug.print("I like {s}\n", .{fruit});
    }
}
I like mango
I like lychee
I like durian

The name between the pipes, |fruit|, is the capture: a constant copy of the current element.

Ranges and indexes

A range start..end produces the integers from start up to, but not including, end. Their type is usize.

zig · try it yourself
const std = @import("std");

pub fn main() void {
    for (0..5) |i| {
        std.debug.print("{d} ", .{i});
    }
    std.debug.print("\n", .{});

    // the index alongside the element: iterate both at once
    const colors = [_][]const u8{ "red", "green", "blue" };
    for (colors, 0..) |color, index| {
        std.debug.print("#{d} {s}\n", .{ index, color });
    }

    // start counting from 1
    for (colors, 1..) |color, n| {
        std.debug.print("{d}. {s}\n", .{ n, color });
    }
}
0 1 2 3 4 
#0 red
#1 green
#2 blue
1. red
2. green
3. blue

A range written as 0.. (no end) takes its length from the other objects in the loop.

Iterating several slices together

You can give for multiple objects separated by commas; each needs its own capture. All of them must have the same length — Zig checks this (at compile time if possible, otherwise with a safety panic).

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const products = [_][]const u8{ "pen", "notebook", "bag" };
    const prices = [_]u32{ 15, 40, 220 };
    const quantities = [_]u32{ 10, 3, 1 };

    var total: u32 = 0;
    for (products, prices, quantities) |name, price, qty| {
        const line = price * qty;
        total += line;
        std.debug.print("{s:<9} {d:>3} x {d:>2} = {d:>4}\n", .{ name, price, qty, line });
    }
    std.debug.print("total: {d}\n", .{total});
}
pen        15 x 10 =  150
notebook   40 x  3 =  120
bag       220 x  1 =  220
total: 490

Modifying elements

Captures are read-only copies. To change elements, loop over a pointer to the array (&array) or a mutable slice, and capture a pointer with |*item|. Then write through it with item.*:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    var prices = [_]f64{ 10.0, 25.5, 8.0 };
    for (&prices) |*p| {
        p.* *= 1.1; // add 10%
    }
    for (prices) |p| std.debug.print("{d:.2} ", .{p});
    std.debug.print("\n", .{});
}
11.00 28.05 8.80 

break, continue and else

break and continue work as in while. A for loop can also have an else that runs if the loop finished without break, so a for can be an expression that searches:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const stock = [_]u32{ 12, 0, 7, 0, 3 };

    var empty_slots: u32 = 0;
    for (stock) |s| {
        if (s != 0) continue;
        empty_slots += 1;
    }

    const first_big: ?usize = for (stock, 0..) |s, i| {
        if (s > 10) break i;
    } else null;

    const first_huge: ?usize = for (stock, 0..) |s, i| {
        if (s > 100) break i;
    } else null;

    std.debug.print("empty={d} big at {?d} huge at {?d}\n", .{ empty_slots, first_big, first_huge });
}
empty=2 big at 0 huge at null

for vs while

Situation Use
visit every element of an array/slice for (items) |x|
count from a to b for (a..b) |i|
step by 2, count down, or complex conditions while with a continue expression
loop until an iterator returns null while (it.next()) |x|

There is no way to make a for range count backwards or skip; use while (i > 0) : (i -= 1) for that.

Test yourself

Which values does for (2..5) |i| produce?

  1. 2, 3, 4, 5
  2. 2, 3, 4
  3. 3, 4, 5
  4. 0 to 5

How do you get both the element and its index?

  1. for (items) |x, i|
  2. for (items, 0..) |x, i|
  3. for (i, x in items)
  4. items.enumerate()

What is required to modify array elements inside a for loop?

  1. Nothing, captures are mutable
  2. Iterate over &array and capture |*x|, then assign x.*
  3. Use var in the capture
  4. It is impossible