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.
Looping over an array
Section titled “Looping over an array”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 appleI like bananaI 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: 55Getting the index too
Section titled “Getting the index too”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: Ana1: Ben2: ChoThe 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”.
Ranges: counting with a..b
Section titled “Ranges: counting with a..b”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 41 squared is 12 squared is 43 squared is 9This 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.
Looping over part of an array
Section titled “Looping over part of an array”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 11 5 9nums[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.
Changing items in place
Section titled “Changing items in place”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.
Looping over several lists at once
Section titled “Looping over several lists at once”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 312. Ben is 253. Cho is 40That’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.
Strings are bytes
Section titled “Strings are bytes”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)for ... else and break with a value
Section titled “for ... else and break with a value”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: 26Any freezing day: falseThe 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.
Practice
Section titled “Practice”1. Find the biggest number
Section titled “1. Find the biggest number”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: 19Starting from the first item (rather than 0) means the code also works when every number is negative.
2. A numbered shopping list
Section titled “2. A numbered shopping list”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. milk2. eggs3. bread1.. starts counting at 1 and takes its length from items, so you never have to write the 3.
3. Double every number
Section titled “3. Double every number”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 ausize. - Ranges
a..bcount fromaup to, but not including,b. - Loop over
items[1..4]to go through part of an array. - To change items, loop over
&itemsand capture|*item|, then writeitem.* = .... - Several lists at once:
for (a, b) |x, y|. They must have the same length. for ... elseplusbreak valuemakes 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: for: ranges, index captures, pointer captures, multi object loops and
else. - Zig language reference: labeled for: breaking out of nested
forloops. - Zig 0.17.0 release notes: what changed in the version this tutorial uses, worth a look when older examples online don’t compile.
- Ziglings: small exercises to fix, several of them about
forloops.