Variables

Variables are declared with var and const:

const std = @import("std");
const print = std.debug.print;

pub fn main() void {
    var a: i64 = 0; // i64 means a 64-bit integer
    a = a + 1;
    print("a = {}\n", .{a});

    var b = a; // type is inferred to be i64
    b = b + 1;
    print("b = {}\n", .{b});

    // If a variable never changes, it must be 'const'.
    const c = true;
    print("c = {}\n", .{c});
}
$ zig run variables.zig 
a = 1
b = 2
c = true

undefined

We can define a variable without initializing it by setting it to undefined:

const std = @import("std");
const print = std.debug.print;

pub fn main() void {
    var a: i64 = undefined;
    a = 3;
    print("a = {}\n", .{a});
}
$ zig run variables-2.zig 
a = 3

We have to make sure we initialize the variable before reading it.

Next example: Illegal Behavior.