Skip to content

Zig Scope

Every name in a program has a scope: the part of the code where you can use it. A variable made inside a loop doesn’t exist after the loop, and a constant at the top of the file can be used everywhere. Zig’s rules here are short, and one of them is stricter than most languages: a name can never hide another name. Knowing these rules will save you from a few confusing compile errors.

A pair of braces { ... } is a block, and every block has its own scope. A name declared inside it exists from its declaration to the closing brace, and then it’s gone:

const std = @import("std");
pub fn main() void {
{
const message = "inside the block";
std.debug.print("{s}\n", .{message});
}
std.debug.print("{s}\n", .{message});
}
main.zig:8:32: error: use of undeclared identifier 'message'
std.debug.print("{s}\n", .{message});
^~~~~~~

Outside the block, message simply isn’t there. It’s the same for the bodies of functions, if, while, for and switch prongs: whatever you declare in them stays in them. If you need a value after the block, declare the variable before it.

The opposite direction works fine: code inside a block can see everything from the blocks around it. That’s why the inner block above can use std, which lives at the top of the file.

Two blocks that sit next to each other, not inside each other, have separate scopes. The first area is gone before the second one is made, so there’s no clash:

const std = @import("std");
pub fn main() void {
const width: u32 = 3;
if (width > 2) {
const area = width * width;
std.debug.print("area inside: {d}\n", .{area});
}
{
const area = width * 10;
std.debug.print("another area: {d}\n", .{area});
}
}

Output:

area inside: 9
another area: 30

Loops are the same. A for body is a fresh block every round, so a const inside it can get a new value each time:

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

Output:

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

square is a const, yet it holds 1, then 4, then 9. That’s not a contradiction: each round makes a brand new square and throws it away at the end of the round. The capture |i| also belongs to the loop body only.

In many languages you can declare a new variable with the same name as one from an outer scope, and the inner one temporarily hides the outer one. That’s called shadowing. Zig doesn’t allow it, anywhere:

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 reason is readability. In Zig, a name means one thing everywhere it can be seen, so you never have to scroll up and work out which total a line is talking about. The reference section on shadowing puts it the same way.

The clash you’ll hit most: function names

Section titled “The clash you’ll hit most: function names”

Shadowing isn’t only about nested blocks. A local name also can’t match anything declared at the top of the file, and that includes your function names. This one catches everyone sooner or later:

const std = @import("std");
fn price(cents: u32) u32 {
return cents;
}
pub fn main() void {
const price = 250;
std.debug.print("{d}\n", .{price});
}
main.zig:8:11: error: local constant shadows declaration of 'price'
const price = 250;
^~~~~
main.zig:3:1: note: declared here
fn price(cents: u32) u32 {
^~

Captures count too. If your file has a function called total, then for (items) |total| fails with capture shadows declaration of 'total', and so does a parameter called total.

Top-level names: visible in the whole file

Section titled “Top-level names: visible in the whole file”

Anything declared outside every function, at the top level of a file, can be used by every function in that file. The order doesn’t matter, so you can use a constant that’s written further down:

const std = @import("std");
pub fn main() void {
std.debug.print("{s} allows {d} players\n", .{ game_name, max_players });
}
const max_players = 4;
const game_name = "Space Rocks";

Output:

Space Rocks allows 4 players

Top-level names are also different from locals in two other ways: they’re only checked if something uses them, and an unused one isn’t an error. The reference calls them namespace-level variables, because a file is a namespace (a container of names) in Zig.

A top-level var is a global variable: there’s only one, it exists for the whole run of the program, and every function can read and change it:

const std = @import("std");
var visits: u32 = 0;
fn visit(page: []const u8) void {
visits += 1;
std.debug.print("visit {d}: {s}\n", .{ visits, page });
}
pub fn main() void {
visit("home");
visit("about");
visit("home");
std.debug.print("total visits: {d}\n", .{visits});
}

Output:

visit 1: home
visit 2: about
visit 3: home
total visits: 3

A global’s starting value has to be known while compiling, so var visits: u32 = 0; is fine, but you can’t start it with something read from the user or a file. Set it later, inside a function, if you need that.

Sometimes one function needs to remember something between calls, like a counter for handing out IDs, without letting the rest of the file touch it. C has static local variables for this. Zig doesn’t have a keyword for it, but you can put a tiny struct inside the function and give it a var:

const std = @import("std");
fn nextId() u32 {
const State = struct {
var counter: u32 = 0;
};
State.counter += 1;
return State.counter;
}
pub fn main() void {
std.debug.print("id {d}\n", .{nextId()});
std.debug.print("id {d}\n", .{nextId()});
std.debug.print("id {d}\n", .{nextId()});
}

Output:

id 1
id 2
id 3

A var declared inside a struct (not a field, a declaration) is a global, so it keeps its value for the whole program. But the name State only exists inside nextId, so no other function can reach the counter. You’ll learn what structs really are in Zig Structs; for now, this is a pattern you can copy. The reference calls it a locally scoped global variable.

This program doesn’t build. Fix it by renaming, so it prints base: 5 and then with bonus: 8.

const std = @import("std");
pub fn main() void {
const score: u32 = 5;
std.debug.print("base: {d}\n", .{score});
{
const score = score + 3;
std.debug.print("with bonus: {d}\n", .{score});
}
}

Hint: the inner score hides the outer one. Give it a name that says what it is.

Show solution
const std = @import("std");
pub fn main() void {
const score: u32 = 5;
std.debug.print("base: {d}\n", .{score});
{
const bonus_score = score + 3;
std.debug.print("with bonus: {d}\n", .{bonus_score});
}
}

Output:

base: 5
with bonus: 8

bonus_score is a different name, so nothing is hidden, and the line reads better too.

Write a function ring() that prints ring 1, ring 2, and so on, counting how many times it’s been called. Call it three times. Use a global variable.

Hint: declare var ring_count: u32 = 0; at the top level and add 1 to it inside ring.

Show solution
const std = @import("std");
var ring_count: u32 = 0;
fn ring() void {
ring_count += 1;
std.debug.print("ring {d}\n", .{ring_count});
}
pub fn main() void {
ring();
ring();
ring();
}

Output:

ring 1
ring 2
ring 3

The global lives for the whole program, so it keeps counting across calls. A local var inside ring would start at 0 every time.

Change your answer to exercise 2 so that only ring can see the counter.

Hint: move the var into a small struct declared inside ring, like nextId in this lesson.

Show solution
const std = @import("std");
fn ring() void {
const Bell = struct {
var count: u32 = 0;
};
Bell.count += 1;
std.debug.print("ring {d}\n", .{Bell.count});
}
pub fn main() void {
ring();
ring();
ring();
}

Output:

ring 1
ring 2
ring 3

The output is the same, but now main (or any other function) can’t change the count by accident.

  • Every block { ... } has its own scope. A name exists from its declaration to the closing brace.
  • Inner code can see outer names, but not the other way around. Blocks side by side can reuse a name.
  • Shadowing is not allowed: a local can’t reuse the name of an outer local, a top-level constant or a function.
  • Top-level names are visible in the whole file, in any order.
  • A top-level var is a global: one copy for the whole program, with a starting value known at compile time. Use them sparingly.
  • A var inside a struct inside a function keeps its value between calls but stays private to that function.

Next up: Zig Function Pointers, how to pass a function to another function, and what to do since Zig has no closures.

Quick check

1. You declare const total = 5; inside an if block. Can you use total after the block ends?
2. Your file has a function fn total() u32. What happens with const total = 10; inside main?
3. Two blocks sit one after the other, and each declares const x. Is that allowed?
4. How do you give a function a counter that keeps its value between calls, without making it visible to other functions?