Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 37 ยท Language Basics

Variables and Constants

Learn how Zig declares names with const and var, why const is the default, type inference, undefined, comptime_int, no-shadowing rules and unused variable errors.

Zig has exactly two ways to declare a local name: const for a value that never changes, and var for one that does. There is no let, no auto and no implicit declaration by assignment. This small vocabulary is one reason Zig programs are easy to read: when you see var, you know to look for later changes.

You will also meet a few rules that surprise newcomers: the compiler refuses unused names, forbids shadowing, and demands that a var actually be modified. These rules exist to catch mistakes early.

const and var

ZIG
const std = @import("std");

pub fn main() void {
    const max_users = 100;      // never changes
    var online: u32 = 0;        // changes later

    online += 5;
    online -= 2;

    std.debug.print("{d} of {d}\n", .{ online, max_users });
}

Output: 3 of 100.

The general form is const name: Type = value; or var name: Type = value;. The type is optional when it can be inferred:

ZIG
const a = 10;          // comptime_int
const b: i64 = 10;     // explicit 64-bit integer
const c = 3.5;         // comptime_float
const d = true;        // bool
const e = "hello";     // pointer to a string literal
const f = @as(u8, 7);  // typed through @as

Assigning to a const is a compile error:

TEXT
error: cannot assign to constant

Use const by default. Switch to var only when the value must change. Zig even helps: if you declare a var that is never modified, the compiler reports local variable is never mutated and asks you to make it const.

comptime_int and comptime_float

A literal such as 10 has the special type comptime_int. It is an arbitrary-precision integer that exists only at compile time. When you store it in a var (a runtime value), Zig needs a concrete type, so this fails:

ZIG
var counter = 0;   // error: variable of type 'comptime_int' must be const or comptime

Fix it by giving the type: var counter: u32 = 0;. A const can keep comptime_int, and it converts to whatever type is needed when used:

ZIG
const limit = 1000;
const small: u8 = 200;
const big: u64 = limit * 1_000_000;   // underscores group digits

Number literals support separators 1_000_000, hexadecimal 0xFF, octal 0o17, binary 0b1010 and floats like 1.5e3.

undefined

A variable must be initialized, but sometimes you want to fill it later, for instance a buffer a function writes into. undefined says "no value yet; I promise to write before reading":

ZIG
var buffer: [64]u8 = undefined;
var result: i32 = undefined;
result = 42;

In Debug builds Zig fills undefined memory with the byte pattern 0xAA, so reading it early produces obviously wrong values. Never read an undefined variable; it is a bug even if the program seems to work.

No shadowing

Zig does not allow an inner scope to reuse the name of an outer one:

ZIG
pub fn main() void {
    const x = 1;
    {
        const x = 2;   // error: local constant shadows declaration of 'x'
        _ = x;
    }
}

This avoids a whole family of bugs where you edit the wrong x. Pick a distinct name instead. (Redeclaring in sibling scopes after the first one ended is fine.)

Unused values are errors

Every local constant, variable and parameter you declare must be used. If you want to deliberately ignore it, assign it to _:

ZIG
fn handler(request: []const u8, verbose: bool) void {
    _ = verbose;               // not needed yet
    std.debug.print("{s}\n", .{request});
}

_ = expression; also discards the result of a function whose return value you do not need. Zig forbids ignoring a returned value silently, so foo(); fails when foo returns something other than void; write _ = foo();.

Scope and blocks

A name lives until the end of the block { ... } that declares it. Blocks are expressions too, and a labeled block can produce a value:

ZIG
const grade = blk: {
    const score = 87;
    if (score >= 90) break :blk 'A';
    if (score >= 80) break :blk 'B';
    break :blk 'C';
};
// grade is 'B'

Labeled blocks let you compute a constant with temporary helper names without leaking them into the surrounding scope.

Globals and constants at file level

Top-level declarations work the same way but are evaluated at compile time when const:

ZIG
const max_retries = 3;
const message = "retrying";
var total_requests: u64 = 0;   // global mutable state; use sparingly

A top-level const that depends on other constants is computed by the compiler, so const kb = 1024; const mb = kb * 1024; costs nothing at runtime.

Stand-ins you can run

C's const and static are the nearest relatives of Zig's constants. This stand-in shows constants, an initialized variable and a deliberately uninitialized buffer that is filled before use.

C Stand-in (C): constants, variables and undefined-like buffers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Rust makes const the default too (let versus let mut), and forbids using values before initialization:

Rust Stand-in (Rust): immutable by default, no uninitialized reads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which declaration is valid in a function body?

    A var needs a concrete runtime type; a bare 0 is a comptime_int, which cannot be stored in a var.
  2. 2. What does var x: i32 = undefined; mean?

    undefined leaves the memory uninitialized; reading it first is a bug.
  3. 3. What does _ = verbose; do?

    Zig rejects unused locals and parameters; assigning to underscore discards them on purpose.
  4. 4. Why is const x = 1; { const x = 2; } rejected?

    No shadowing keeps readers from mixing up two different variables with one name.
  5. 5. Which is the best default for a value that never changes?

    Prefer const, and the compiler will tell you when a var is never mutated.

Summary

  • const for values that never change, var for values that do; prefer const.
  • Types are inferred when possible; a runtime var needs a concrete type because literals are comptime_int or comptime_float.
  • undefined means "to be written before reading", never "zero".
  • Zig forbids shadowing, unused locals and parameters (use _ = x;), and silently ignoring return values.
  • Labeled blocks (blk: { break :blk value; }) compute a value with private helper names.

Next: Integers and Floating-Point Numbers