🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Variables

A variable is a named place that holds a value. Zig uses const for a value that stays the same and var for a value that can change.

A const holds its value

const sets score once. The print line then reads that stored value.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const score = 10;
    try out.print("Score: {d}\n", .{score});
}

A var can change its value

ready starts as false. A later line gives it a new value, and the second print shows the change.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    var ready = false;
    try out.print("Ready: {}\n", .{ready});
    ready = true;
    try out.print("Ready: {}\n", .{ready});
}

A const cannot be assigned again

This program does not compile. Zig reports that a const name cannot take a new value.

pub fn main() void {
    const x = 5;
    x = 6;
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const tickets = 4;
    var ready = false;
    try out.print("Tickets: {d}\n", .{tickets});
    try out.print("Ready: {}\n", .{ready});
    ready = true;
    try out.print("Ready: {}\n", .{ready});
}

Key points

  • Name: each stored value gets a name, and later lines can use that name.
  • const: const binds a name to a value that cannot change after it is set.
  • var: var binds a name to a value that can change while the program runs.
  • Assignment: the = sign stores the value on its right under the name on its left.
  • Reassignment: a var can get a new value from another assignment line.
  • Use const when the value stays the same, and use var only when the value must change.

In this example, tickets is a const, so it keeps the value 4 for the whole program. ready is a var, so the later assignment changes it from false to true.

Note

Zig reports an error if a line tries to assign a new value to a const name.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which keyword creates a name whose value can change while the program runs?