Skip to content

Variables and Constants

A program works with values. In Zig, values are usually stored in constants or variables.

A program works with values. In Zig, values are usually stored in constants or variables.

A constant is declared with const:

const std = @import("std");

pub fn main() void {
    const year = 2026;

    std.debug.print("{d}\n", .{year});
}

Run it:

2026

The name year cannot be changed after it is declared.

A variable is declared with var:

const std = @import("std");

pub fn main() void {
    var count = 1;

    count = count + 1;

    std.debug.print("{d}\n", .{count});
}

The output is:

2

A variable may change during the execution of the program.

Use const unless the value must change. Most names in Zig programs are constants.

The statement:

count = count + 1;

reads the current value of count, adds one, and stores the result back into count.

This is common enough that Zig provides a shorter form:

count += 1;

The two forms are equivalent.

Variables and constants have types. In many cases Zig can infer the type automatically:

const number = 10;

Here number is an integer.

const pi = 3.14159;

Here pi is a floating-point value.

The type can also be written explicitly:

const number: i32 = 10;

i32 means a signed 32-bit integer.

const distance: f64 = 12.5;

f64 means a 64-bit floating-point value.

A declaration has this general form:

const name: type = value;

or:

var name: type = value;

The type comes after the colon.

The value comes after the equals sign.

A name must be declared before it is used.

This program is wrong:

const std = @import("std");

pub fn main() void {
    value = 10;
}

value has not been declared.

Write it this way:

const std = @import("std");

pub fn main() void {
    const value = 10;

    std.debug.print("{d}\n", .{value});
}

A declaration may appear almost anywhere inside a block:

const std = @import("std");

pub fn main() void {
    const a = 10;

    {
        const b = 20;
        std.debug.print("{d}\n", .{b});
    }

    std.debug.print("{d}\n", .{a});
}

The name b exists only inside the inner block.

Blocks control lifetime and visibility.

Exercise 1-9. Declare a variable named total and add 5 to it.

Exercise 1-10. Declare a constant named pi with the value 3.14.

Exercise 1-11. Change a const value after declaration. Read the compiler error.

Exercise 1-12. Declare an i64 value and print it with {d}.