Skip to content

Zig Variables

A variable is a name for a value, like age holding 36 or name holding "Ada". You’ll write them in almost every line of Zig. Zig has two keywords for this: const for values that never change and var for values that do. The compiler is strict about which one you pick, and about names you create but never use. That feels fussy on day one, but it catches real bugs, so this page explains the why behind each rule.

Most of the time you’ll use const. You write const, a name, = and a value:

const std = @import("std");
pub fn main() void {
const name = "Ada";
const age = 36;
std.debug.print("{s} is {d} years old\n", .{ name, age });
}

Output:

Ada is 36 years old

const age = 36; makes a name age that holds 36 from now until the end of the block. You’ve already seen this pattern on the first line of every program: const std = @import("std"); is just a constant whose value is the standard library.

If you try to change a constant, the compiler stops you:

const std = @import("std");
pub fn main() void {
const lives = 3;
lives = 2;
std.debug.print("{d}\n", .{lives});
}
main.zig:5:5: error: cannot assign to constant
lives = 2;
^~~~~

When a value really needs to change, use var. A var also needs a type, written after a colon:

const std = @import("std");
pub fn main() void {
var score: u32 = 0;
std.debug.print("start: {d}\n", .{score});
score = 10;
score += 5;
std.debug.print("now: {d}\n", .{score});
}

Output:

start: 0
now: 15

var score: u32 = 0; creates a variable called score of type u32 (a whole number that can’t be negative, more on that in Zig Integers). After that, you change it with plain = or a shortcut like +=, without writing var again.

Why does var need a type when const didn’t? Leave it out and see:

const std = @import("std");
pub fn main() void {
var score = 0;
score += 5;
std.debug.print("{d}\n", .{score});
}
main.zig:4:9: error: variable of type 'comptime_int' must be const or comptime
var score = 0;
^~~~~
main.zig:4:9: note: to modify this variable at runtime, it must be given an explicit fixed-size number type

A plain number like 0 has the special type comptime_int: a number with no fixed size that only exists while the compiler runs. A variable that changes while your program runs needs a real size in memory (8 bits? 32? 64?), and Zig won’t guess for you. So you pick one: var score: u32 = 0;. With const there’s nothing to store at runtime, so no size is needed.

Here’s a rule that surprises everyone at first. If you write var but never change the value, it’s a compile error:

const std = @import("std");
pub fn main() void {
var total: i32 = 100;
std.debug.print("{d}\n", .{total});
}
main.zig:4:9: error: local variable is never mutated
var total: i32 = 100;
^~~~~
main.zig:4:9: note: consider using 'const'

“Mutated” just means “changed”. The fix is to do what the note says and write const total: i32 = 100;.

Why so strict? When you read someone else’s code, const is a promise: this value is the same everywhere below. If var were allowed for values that never change, that promise would be worth less. The official reference puts it plainly in its section on variables: prefer const, because it’s less work for both people and the compiler.

Zig also refuses to build if you create a local name and never use it:

const std = @import("std");
pub fn main() void {
const width = 80;
const height = 24;
std.debug.print("width: {d}\n", .{width});
}
main.zig:5:11: error: unused local constant
const height = 24;
^~~~~~

For a var the message says unused local variable instead. An unused name is often a sign of a bug: you computed something and then forgot to use it, or used the wrong name somewhere else.

While you’re in the middle of writing code, you can tell the compiler “I know, ignore this one” by assigning it to _, the discard:

const std = @import("std");
pub fn main() void {
const width = 80;
const height = 24;
_ = height; // not used yet
std.debug.print("width: {d}\n", .{width});
}

Output:

width: 80

You’ll also see _ = &x; in short examples, including the official docs and later pages of this tutorial. It looks odd, but it just takes the address of x and throws it away. Because something could change x through that address, the compiler stops saying “never mutated”. It’s a trick for demos that need a var whose value the compiler can’t predict. In real code you don’t need it.

Every value in Zig has a type. With const, Zig usually works it out from the value. That’s called type inference. You can also write the type yourself after a colon, which is a type annotation:

const std = @import("std");
pub fn main() void {
const count: u8 = 3;
const price: f64 = 4.5;
const in_stock: bool = true;
const title: []const u8 = "Receipt";
std.debug.print("{s}: {d} items at {d} each, in stock: {}\n", .{ title, count, price, in_stock });
}

Output:

Receipt: 3 items at 4.5 each, in stock: true

u8 is a small whole number, f64 a decimal number, bool is true or false, and []const u8 is Zig’s usual type for text. Each one gets its own page in this section. A variable’s type never changes, so once count is a u8 it can only ever hold u8 values:

const std = @import("std");
pub fn main() void {
var count: u8 = 3;
count = "three";
std.debug.print("{d}\n", .{count});
}
main.zig:5:13: error: expected type 'u8', found '*const [5:0]u8'
count = "three";
^~~~~~~

The odd-looking *const [5:0]u8 is the type of the text "three". You’ll learn to read it in Zig Strings.

Every variable must get a value when you create it. Leaving the = off is a syntax error:

const std = @import("std");
pub fn main() void {
var answer: i32;
answer = 42;
std.debug.print("{d}\n", .{answer});
}
main.zig:4:20: error: expected '=', found ';'
var answer: i32;
^

When you really don’t have a value yet, say so on purpose with undefined:

const std = @import("std");
pub fn main() void {
const hour: u8 = 14;
var greeting: []const u8 = undefined;
if (hour < 12) {
greeting = "Good morning";
} else {
greeting = "Good afternoon";
}
std.debug.print("{s}\n", .{greeting});
}

Output:

Good afternoon

undefined means “there’s no meaningful value here yet, and reading it would be a bug”. It’s up to you to set the variable before you read it. Zig does not check that for you. If you print a variable that’s still undefined, you get whatever bytes happen to be in memory. In debug builds Zig fills that memory with the byte 0xaa, so an i32 shows up as -1431655766, a clue that you read something you never set. The reference section on undefined explains that this pattern is a debugging help, not a promise.

In some languages you can create a new variable with the same name as one in an outer block. That’s called shadowing. Zig doesn’t allow it:

const std = @import("std");
pub fn main() void {
const level = 1;
{
const level = 2;
std.debug.print("inner: {d}\n", .{level});
}
std.debug.print("outer: {d}\n", .{level});
}
main.zig:6:15: error: local constant 'level' shadows local constant from outer scope
const level = 2;
^~~~~
main.zig:4:11: note: previous declaration here
const level = 1;
^~~~~

The { ... } is a block: a group of statements with its own scope. The benefit of the rule is that a name always means one thing inside its scope, so you never have to wonder which level a line is using. Pick a new name instead, like inner_level. Two blocks next to each other can reuse a name, because their scopes don’t overlap. You’ll see more of this in Zig Scope.

Rust developers, note this one: let x = x + 1; style shadowing has no direct match in Zig. Use a new name or a var.

You can also declare constants at the top of a file, outside any function. These are called container-level declarations, and every function in the file can use them:

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

Output:

Space Rocks supports 4 players

This is the usual home for settings and magic numbers, so they have a name and live in one place. Top-level names can be used before the line that declares them, and the unused-name rule doesn’t apply to them (only to locals).

This program should print clicks: 3, but it has two mistakes. Fix both.

const std = @import("std");
pub fn main() void {
const clicks = 0;
const unused = 99;
clicks += 3;
std.debug.print("clicks: {d}\n", .{clicks});
}

Hint: one name needs to change, so it needs var and a type. The other name isn’t used at all.

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

Output:

clicks: 3

clicks changes, so it’s a var with a real type (u32). The unused constant is simply deleted. Writing _ = unused; would also build, but there’s no reason to keep a value you never need.

Create a variable size of type []const u8 set to undefined. Then, using a constant width: u32 = 1200, set size to "large" if width is greater than 1000, otherwise "small". Print size: large.

Hint: copy the shape of the greeting example above.

Show solution
const std = @import("std");
pub fn main() void {
const width: u32 = 1200;
var size: []const u8 = undefined;
if (width > 1000) {
size = "large";
} else {
size = "small";
}
std.debug.print("size: {s}\n", .{size});
}

Output:

size: large

Both branches set size, so it always has a real value before print reads it. width never changes, so it’s a const.

This code doesn’t build because price is declared twice. Make it print both prices.

const std = @import("std");
pub fn main() void {
const price: u32 = 100;
{
const price: u32 = price * 2;
std.debug.print("double: {d}\n", .{price});
}
std.debug.print("price: {d}\n", .{price});
}

Hint: give the inner one its own name.

Show solution
const std = @import("std");
pub fn main() void {
const price: u32 = 100;
{
const double_price: u32 = price * 2;
std.debug.print("double: {d}\n", .{double_price});
}
std.debug.print("price: {d}\n", .{price});
}

Output:

double: 200
price: 100

The inner block can still read the outer price. It just can’t create a second name price while the first one is in scope.

  • Use const for values that don’t change, and that’s most of them. Use var only when the value changes.
  • A var needs a fixed-size type like u32, because a bare number is a comptime_int with no size.
  • A var that’s never changed is an error (“local variable is never mutated”), and so is an unused local. Discard on purpose with _ = x;.
  • Every variable gets a value when it’s created. Use undefined to say “set below”, and make sure you really do set it before reading.
  • Zig has no shadowing: a name can’t be reused while an outer one with the same name is in scope.
  • Container-level constants at the top of a file are shared by every function in it.

Next up: Zig Data Types, a tour of every kind of value a variable can hold.

Quick check

1. You write var total: i32 = 100; and only ever read total. What happens?
2. Why does var count = 0; fail to build?
3. What does var buf: [64]u8 = undefined; mean?
4. Inside a block, you write const level = 2; while an outer level exists. What happens?