Skip to content

Zig For

Most loops in real programs go through a list of things: every score in a game, every line in a file, every byte in a string. Zig’s for loop is made for exactly that. It feels like Python’s for x in items or JavaScript’s for...of, and it’s not C’s for (int i = 0; i < n; i++). For counting loops, Zig gives you ranges like 0..10 instead, and you’ll see both on this page.

You give for the thing to loop over, and a name between bars |...| for the current item. This name is called a capture:

const std = @import("std");
pub fn main() void {
const fruits = [_][]const u8{ "apple", "banana", "cherry" };
for (fruits) |fruit| {
std.debug.print("I like {s}\n", .{fruit});
}
}

Output:

I like apple
I like banana
I like cherry

[_][]const u8{ ... } is an array of strings (_ lets Zig count them for you; there’s more in Zig Arrays). The loop runs once per item, and each time fruit is the current one. There’s no counter to set up, no length to check and no way to go one past the end.

Here’s a loop that does some work, adding up a list of prices:

const std = @import("std");
pub fn main() void {
const prices = [_]u32{ 12, 5, 30, 8 };
var total: u32 = 0;
for (prices) |price| {
total += price;
}
std.debug.print("Total: {d}\n", .{total});
}

Output:

Total: 55

Often you need to know where you are, not just what you’re looking at. Add a second thing to loop over, 0.., and a second capture. 0.. counts up from 0, one step per item:

const std = @import("std");
pub fn main() void {
const players = [_][]const u8{ "Ana", "Ben", "Cho" };
for (players, 0..) |name, i| {
std.debug.print("{d}: {s}\n", .{ i, name });
}
}

Output:

0: Ana
1: Ben
2: Cho

The captures line up with what you’re looping over: name comes from players, i comes from 0... The index i is a usize, the type Zig uses for sizes and positions. Want to number from 1 instead? Write 1...

If you ask for a capture and don’t use it, Zig complains, just like it does for unused variables:

const std = @import("std");
pub fn main() void {
const players = [_][]const u8{ "Ana", "Ben", "Cho" };
for (players, 0..) |name, i| {
std.debug.print("{s}\n", .{name});
}
}
main.zig:6:31: error: unused capture
for (players, 0..) |name, i| {
^

Drop the , 0.. and , i if you don’t need the index, or write _ in its place (|name, _|) to say “I know, I’m ignoring it”.

To loop over numbers instead of a list, use a range. 0..5 gives 0, 1, 2, 3 and 4: it starts at the first number and stops just before the second:

const std = @import("std");
pub fn main() void {
for (0..5) |i| {
std.debug.print("{d} ", .{i});
}
std.debug.print("\n", .{});
for (1..4) |n| {
std.debug.print("{d} squared is {d}\n", .{ n, n * n });
}
}

Output:

0 1 2 3 4
1 squared is 1
2 squared is 4
3 squared is 9

This is Python’s range(0, 5) and the usual replacement for C’s counting for. The number of rounds is simply end - start. The end can be a variable too, like for (0..count) |i|.

Ranges only count up, one at a time. To count down or take bigger steps, use a while loop with a continue expression, as in Zig While.

To go through only some of the items, loop over a slice of the array. nums[1..4] means “items 1, 2 and 3”, using the same “end not included” rule as ranges:

const std = @import("std");
pub fn main() void {
const nums = [_]i32{ 3, 1, 4, 1, 5, 9 };
for (nums[1..4]) |n| {
std.debug.print("{d} ", .{n});
}
std.debug.print("\n", .{});
for (nums[3..]) |n| {
std.debug.print("{d} ", .{n});
}
std.debug.print("\n", .{});
}

Output:

1 4 1
1 5 9

nums[3..] with no end means “from index 3 to the end”. for works the same on arrays and slices; Zig Slices explains what a slice really is.

The capture is a copy of the item, and it’s constant. So this doesn’t work:

const std = @import("std");
pub fn main() void {
const scores = [_]u32{ 70, 85, 90 };
for (scores) |score| {
score += 5;
}
std.debug.print("{any}\n", .{scores});
}
main.zig:7:9: error: cannot assign to constant
score += 5;
^~~~~

To change the items themselves, loop over &scores (a pointer to the array) and capture |*score|, a pointer to each item. Then score.* is the item itself:

const std = @import("std");
pub fn main() void {
var scores = [_]u32{ 70, 85, 90 };
for (&scores) |*score| {
score.* += 5;
}
std.debug.print("{any}\n", .{scores});
}

Output:

{ 75, 90, 95 }

Three small changes: the array is now a var (so it can change), you loop over &scores, and you capture *score. score.* means “the value this pointer points to”. If pointers are new to you, that’s fine: copy this pattern for now, and Zig Pointers will explain it. {any} prints the whole array.

for can walk through several lists side by side. Put them all in the parentheses and give one capture for each:

const std = @import("std");
pub fn main() void {
const names = [_][]const u8{ "Ana", "Ben", "Cho" };
const ages = [_]u8{ 31, 25, 40 };
for (names, ages, 1..) |name, age, place| {
std.debug.print("{d}. {s} is {d}\n", .{ place, name, age });
}
}

Output:

1. Ana is 31
2. Ben is 25
3. Cho is 40

That’s how 0.. worked earlier: it’s just one more thing to loop over, and it takes its length from the others. The language reference on for calls this a “multi object for”.

The lists must all have the same length. If Zig can see the lengths while compiling, it tells you right away:

const std = @import("std");
pub fn main() void {
const names = [_][]const u8{ "Ana", "Ben", "Cho" };
const ages = [_]u8{ 31, 25 };
for (names, ages) |name, age| {
std.debug.print("{s} is {d}\n", .{ name, age });
}
}
main.zig:7:5: error: non-matching for loop lengths
for (names, ages) |name, age| {
^~~
main.zig:7:10: note: length 3 here
for (names, ages) |name, age| {
^~~~~
main.zig:7:17: note: length 2 here
for (names, ages) |name, age| {
^~~~

If the lengths are only known while the program runs (slices of different sizes, for example), a debug build stops with a panic instead: panic: for loop over objects with non-equal lengths. Either way, you never read past the end of the shorter list.

A string in Zig is a list of bytes (u8), so for over a string gives you one byte at a time. Use {c} to print a byte as a character:

const std = @import("std");
pub fn main() void {
const word = "Zig";
for (word, 0..) |c, i| {
std.debug.print("{d}: {c} (byte {d})\n", .{ i, c, c });
}
}

Output:

0: Z (byte 90)
1: i (byte 105)
2: g (byte 103)

Like while, a for loop can have an else that runs when the loop finishes without a break. Together with break value, the whole loop becomes an expression with a result:

const std = @import("std");
pub fn main() void {
const temps = [_]i32{ 18, 21, 26, 30, 24 };
const first_hot: i32 = for (temps) |t| {
if (t > 25) break t;
} else -1;
std.debug.print("First hot day: {d}\n", .{first_hot});
const freezing: bool = for (temps) |t| {
if (t < 0) break true;
} else false;
std.debug.print("Any freezing day: {}\n", .{freezing});
}

Output:

First hot day: 26
Any freezing day: false

The first loop hits 26, so break t makes 26 the result. The second loop never breaks, so the else gives false. break and labels get a full page in Zig Break/Continue.

Loop over [_]i32{ 7, -2, 19, 4, 11 } and print the biggest number.

Hint: start a var biggest at the first item (nums[0]), and replace it whenever you see a bigger one.

Show solution
const std = @import("std");
pub fn main() void {
const nums = [_]i32{ 7, -2, 19, 4, 11 };
var biggest = nums[0];
for (nums) |n| {
if (n > biggest) biggest = n;
}
std.debug.print("Biggest: {d}\n", .{biggest});
}

Output:

Biggest: 19

Starting from the first item (rather than 0) means the code also works when every number is negative.

Print the list milk, eggs, bread as 1. milk, 2. eggs, 3. bread.

Hint: loop over the list and 1.. together.

Show solution
const std = @import("std");
pub fn main() void {
const items = [_][]const u8{ "milk", "eggs", "bread" };
for (items, 1..) |item, n| {
std.debug.print("{d}. {s}\n", .{ n, item });
}
}

Output:

1. milk
2. eggs
3. bread

1.. starts counting at 1 and takes its length from items, so you never have to write the 3.

Change every number in [_]u32{ 1, 2, 3, 4 } to twice its value, in place, then print the array.

Hint: the array must be a var, and you need & and |*n|.

Show solution
const std = @import("std");
pub fn main() void {
var nums = [_]u32{ 1, 2, 3, 4 };
for (&nums) |*n| {
n.* *= 2;
}
std.debug.print("{any}\n", .{nums});
}

Output:

{ 2, 4, 6, 8 }

n points at each item in turn, and n.* *= 2 changes the item itself, not a copy.

  • for (items) |item| { ... } runs once per item. The capture is a constant copy.
  • Add 0.. and a second capture to get the index: for (items, 0..) |item, i|. The index is a usize.
  • Ranges a..b count from a up to, but not including, b.
  • Loop over items[1..4] to go through part of an array.
  • To change items, loop over &items and capture |*item|, then write item.* = ....
  • Several lists at once: for (a, b) |x, y|. They must have the same length.
  • for ... else plus break value makes the loop produce a value.

Next up: Zig Break/Continue, including labeled loops and how to break out of two loops at once.

Quick check

1. Which numbers does for (2..5) |n| go through?
2. How do you get the index of each item?
3. Why does for (scores) |s| { s += 1; } fail to compile?
4. What happens with for (a, b) |x, y| if a has 3 items and b has 2?