TExcelTAD
Home › Zig › Zig Variables & Constants

Zig Variables & Constants

A variable is a named place that holds a value. Zig has two keywords for creating one, and choosing between them is one of the first habits the language teaches you.

Keyword Can change? Use it when
const no the value is fixed after it is set (most of the time)
var yes the value really must change later

const and var

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const city = "Hanoi";
    var visitors: u32 = 120;

    visitors += 30; // allowed: visitors is a var
    visitors = visitors * 2;

    std.debug.print("{s} had {d} visitors\n", .{ city, visitors });
}
Hanoi had 300 visitors

Trying to change a constant is a compile error ("cannot assign to constant"). The opposite mistake is also an error: a var that is never changed.

zig · try it yourself
const std = @import("std");

pub fn main() void {
    var lives: u8 = 3;
    std.debug.print("lives: {d}\n", .{lives});
}
./example.zig:4:9: error: local variable is never mutated
    var lives: u8 = 3;
        ^~~~~
./example.zig:4:9: note: consider using 'const'

This rule means that whenever you see var, you know the value changes somewhere below. Prefer const by default.

Types and type inference

The type goes after the name, separated by a colon. If you leave it out, Zig infers it from the value.

zig
const a: i32 = 10;    // explicit type
const b = @as(i64, 5); // explicit type via @as
const c = 2.5;        // inferred: comptime_float

A var usually needs an explicit type. A bare number literal like 10 has the special type comptime_int, which exists only at compile time, so var x = 10; does not compile — write var x: i32 = 10; instead.

Variables must be initialised

Every variable needs a value when it is declared. If you really have nothing to put there yet, use undefined, which tells Zig "this memory has no meaningful value yet":

zig · try it yourself
const std = @import("std");

pub fn main() void {
    var result: i32 = undefined;
    const ready = true;

    if (ready) {
        result = 42;
    } else {
        result = -1;
    }
    std.debug.print("result = {d}\n", .{result});
}
result = 42

Note: Reading an undefined value before assigning it is a bug. In Debug builds Zig fills such memory with the byte 0xaa, so mistakes tend to show up as strange numbers like 170 or -1431655766.

Top-level constants

Declarations outside any function live for the whole program and can be used before the line where they appear — order does not matter at the top level.

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const seconds = minutes_per_day * 60;
    std.debug.print("{d} minutes, {d} seconds per day\n", .{ minutes_per_day, seconds });
}

const hours_per_day = 24;
const minutes_per_day = hours_per_day * 60;
1440 minutes, 86400 seconds per day

Top-level vars also exist (they are global variables), but they are rare in idiomatic Zig.

Shadowing is not allowed

Zig does not let an inner variable reuse the name of an outer one. This avoids the confusion of two different counts in the same function:

zig
const count = 1;
{
    const count = 2; // error: local constant 'count' shadows local constant from outer scope
}

Pick a more descriptive name instead, such as inner_count.

Destructuring

Since tuples and arrays have a known length, you can unpack them into several names at once:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const point = .{ 3, 4 };
    const x, const y = point;

    var low: i32 = 0;
    var high: i32 = 0;
    low, high = .{ 10, 20 };
    high += 1;
    low -= 1;

    std.debug.print("x={d} y={d} low={d} high={d}\n", .{ x, y, low, high });
}
x=3 y=4 low=9 high=21

Test yourself

Which declaration compiles?

  1. var n = 5;
  2. var n: i32 = 5; (and n is later modified)
  3. const n: i32; n = 5;
  4. let n = 5;

What does undefined mean as an initial value?

  1. Zero
  2. Null
  3. The memory has no meaningful value yet
  4. A compile error

What happens if an inner block declares a constant with the same name as an outer one?

  1. The inner one hides the outer
  2. Compile error: shadowing is not allowed
  3. The outer one is overwritten
  4. It is allowed only with var