Zig Blocks
A block is just some code between curly braces { ... }. You’ve been writing them all along: the body of main, the branches of an if, the body of a loop. In Zig a block can also stand on its own, to keep a few temporary variables tidy, and with a label it can work out a value and hand it back. That last trick shows up all over real Zig code, usually as blk: { ... break :blk x; }, so it’s worth knowing well.
A block limits where a variable exists
Section titled “A block limits where a variable exists”A variable created inside a block only exists until that block’s closing brace. This is called its scope:
const std = @import("std");
pub fn main() void { const price: u32 = 40;
{ const discount: u32 = 5; std.debug.print("inside: {d}\n", .{price - discount}); }
std.debug.print("outside: {d}\n", .{price});}Output:
inside: 35outside: 40The inner block can see price, because it comes from the outer block. But discount is gone once the inner block ends. If you try to use it afterwards:
const std = @import("std");
pub fn main() void { { const discount: u32 = 5; std.debug.print("inside: {d}\n", .{discount}); } std.debug.print("outside: {d}\n", .{discount});}main.zig:8:41: error: use of undeclared identifier 'discount' std.debug.print("outside: {d}\n", .{discount}); ^~~~~~~~Why would you want this? A bare block is a handy way to say “these few variables are only needed for this bit”. Nobody further down can use them by mistake, and you can reuse the same short names in the next block.
No shadowing
Section titled “No shadowing”Many languages let an inner block create a new variable with the same name as an outer one, hiding it for a while. That’s called shadowing, and Zig doesn’t allow it:
const std = @import("std");
pub fn main() void { const total: u32 = 10; { const total: u32 = 20; std.debug.print("{d}\n", .{total}); } std.debug.print("{d}\n", .{total});}main.zig:6:15: error: local constant 'total' shadows local constant from outer scope const total: u32 = 20; ^~~~~main.zig:4:11: note: previous declaration here const total: u32 = 10; ^~~~~The idea is that a name always means one thing while you’re reading a piece of code, so you never have to work out which total you’re looking at. Two blocks side by side can use the same name, though, because their scopes don’t overlap. Zig Scope goes deeper into this.
Labeled blocks: a block that gives a value
Section titled “Labeled blocks: a block that gives a value”Sometimes a value takes a few steps to work out. In Zig you can put those steps in a block, give the block a label, and use break :label value to send the value out:
const std = @import("std");
pub fn main() void { const width: u32 = 3; const height: u32 = 4;
const diagonal_squared = blk: { const a = width * width; const b = height * height; break :blk a + b; };
std.debug.print("diagonal squared: {d}\n", .{diagonal_squared});}Output:
diagonal squared: 25Read blk: { ... break :blk a + b; } as “run this block; its value is whatever break :blk says”. The label blk is just a name (short for “block”), and it’s the one you’ll see most in Zig code, but any name works. The helper values a and b stay inside the block, and diagonal_squared can be a const even though it took three lines to compute.
Several exits from one block
Section titled “Several exits from one block”A labeled block can break in more than one place. The first break that runs decides the value:
const std = @import("std");
fn describe(n: i32) void { const kind = blk: { if (n == 0) break :blk "zero"; if (n < 0) break :blk "negative"; if (@mod(n, 2) == 0) break :blk "positive and even"; break :blk "positive and odd"; }; std.debug.print("{d} is {s}\n", .{ n, kind });}
pub fn main() void { describe(0); describe(-3); describe(8); describe(7);}Output:
0 is zero-3 is negative8 is positive and even7 is positive and oddfn describe is a small function so we can test four values; you’ll meet functions in Zig Functions. @mod(n, 2) is the remainder after dividing by 2, and it’s the safe choice for signed numbers like i32. This “check, check, check, default” shape is often easier to read than a long if ... else if chain.
Blocks inside switch and if
Section titled “Blocks inside switch and if”A labeled block can go anywhere a value can, including a switch prong. That’s useful when one prong needs a bit of work:
const std = @import("std");
const Size = enum { small, medium, large };
fn price(size: Size, extra_shot: bool) u32 { return switch (size) { .small => 3, .medium => 4, .large => blk: { var p: u32 = 5; if (extra_shot) p += 1; break :blk p; }, };}
pub fn main() void { std.debug.print("small: {d}\n", .{price(.small, false)}); std.debug.print("large with extra shot: {d}\n", .{price(.large, true)});}Output:
small: 3large with extra shot: 6Size is an enum, a type with a fixed list of named values (see Zig Enums). The .large prong uses a small block with its own var p, which no other prong can see.
Two mistakes with labeled blocks
Section titled “Two mistakes with labeled blocks”Forgetting the label on break. A plain break belongs to loops, so inside a block it’s an error:
const std = @import("std");
pub fn main() void { const x = blk: { break 5; }; std.debug.print("{d}\n", .{x});}main.zig:5:9: error: break expression outside loop break 5; ^~~~~~~Write break :blk 5; instead.
Leaving a path without a break. If the block can reach its closing brace without hitting a break :blk, that path has no value (it’s void), and the types don’t match:
const std = @import("std");
fn label(n: u32) []const u8 { const kind = blk: { if (n == 0) break :blk "zero"; }; return kind;}
pub fn main() void { std.debug.print("{s}\n", .{label(0)});}main.zig:4:23: error: incompatible types: '*const [4:0]u8' and 'void' const kind = blk: { ~~~~~^main.zig:5:32: note: type '*const [4:0]u8' here if (n == 0) break :blk "zero"; ^~~~~~The fix is a final break :blk ...; at the end of the block, for the “none of the above” case.
Practice
Section titled “Practice”1. Keep the helpers inside
Section titled “1. Keep the helpers inside”Compute the area of a ring with outer radius 10 and inner radius 4, using whole numbers and 3 as a rough value of pi. Use a labeled block so the helper values stay inside it, and print the result.
Hint: const area = blk: { const outer = 10 * 10; const inner = 4 * 4; break :blk 3 * (outer - inner); };
Show solution
const std = @import("std");
pub fn main() void { const area: u32 = blk: { const outer: u32 = 10 * 10; const inner: u32 = 4 * 4; break :blk 3 * (outer - inner); };
std.debug.print("Ring area (rough): {d}\n", .{area});}Output:
Ring area (rough): 252outer and inner only exist inside the block, and area is a single const with the final answer.
2. Fizz, buzz or the number
Section titled “2. Fizz, buzz or the number”For n from 1 to 15, use a labeled block to pick the text: "FizzBuzz" if n divides by 15, "Fizz" if by 3, "Buzz" if by 5, and "-" otherwise. Print n and the text.
Hint: check 15 first, then 3, then 5, each with its own break :blk.
Show solution
const std = @import("std");
pub fn main() void { for (1..16) |n| { const text = blk: { if (n % 15 == 0) break :blk "FizzBuzz"; if (n % 3 == 0) break :blk "Fizz"; if (n % 5 == 0) break :blk "Buzz"; break :blk "-"; }; std.debug.print("{d}: {s}\n", .{ n, text }); }}Output:
1: -2: -3: Fizz4: -5: Buzz6: Fizz7: -8: -9: Fizz10: Buzz11: -12: Fizz13: -14: -15: FizzBuzzThe first break :blk that runs picks the text, so checking 15 first matters.
3. Fix the block
Section titled “3. Fix the block”This program should print Temperature is warm, but it doesn’t compile. Fix it.
const std = @import("std");
pub fn main() void { const celsius: i32 = 22; const word = feel: { if (celsius < 10) break "cold"; if (celsius < 25) break "warm"; break "hot"; }; std.debug.print("Temperature is {s}\n", .{word});}Hint: each break must say which block it leaves.
Show solution
const std = @import("std");
pub fn main() void { const celsius: i32 = 22; const word = feel: { if (celsius < 10) break :feel "cold"; if (celsius < 25) break :feel "warm"; break :feel "hot"; }; std.debug.print("Temperature is {s}\n", .{word});}Output:
Temperature is warmThe label here is feel, so every break needs :feel. A plain break only works for loops.
- A block is code in
{ ... }. Variables made inside it disappear at the closing brace. - Zig has no shadowing: an inner block can’t reuse a name from an outer one. Side-by-side blocks can.
- A labeled block
blk: { ... break :blk value; }produces a value, which lets the result be aconst. - A block can
breakfrom several places; the first one that runs wins. breakinside a block needs the label, and every path must end in abreak :label.- An empty block
{}has the typevoid.
Next up: Zig Defer, a way to make sure cleanup code runs when a block ends.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: blocks: scope, labeled blocks and empty blocks.
- Zig language reference: shadowing: why the same name can’t be reused in an inner scope.
- Zig in-depth overview: the official tour, including “no hidden control flow”.
- Ziglings: practice exercises, including labeled blocks.