Variables, Constants and undefined

4.1 const and var

Prefer const. The compiler errors if a var is never mutated ("local variable is never mutated").

A var with a comptime literal needs an explicit type: var x: u32 = 5; (var x = 5; is an error, because comptime_int can't be a runtime variable).

const pi = 3.14159;            // immutable; type inferred (comptime_float)
const age: u8 = 30;            // explicit type
var count: i32 = 0;            // mutable: requires a type (or a typed initializer)
count += 1;
var name = "zig";              // a var of type *const [3:0]u8

4.2 undefined

In Debug mode, undefined memory is filled with 0xAA to help catch bugs. Reading undefined memory is illegal behavior.

var buffer: [256]u8 = undefined;   // uninitialized memory: must be written before it's read
var x: i32 = undefined;
x = 42;

4.3 Shadowing Is Not Allowed

A local variable can't have the same name as one in an outer scope. This prevents confusion.

4.4 Container-Level (Global) Variables

var global_counter: u32 = 0;                  // mutable global (static lifetime)
threadlocal var tls_value: i32 = 0;           // thread-local
const lookup = [_]u8{ 1, 2, 3 };              // global constant (comptime-known)

4.5 Destructuring (0.12+)

const a, const b = .{ 1, 2 };                 // tuple destructuring
var x: u32, var y: u32 = .{ 10, 20 };
const q, const r = divmod(17, 5);             // a function returning a tuple

4.6 Blocks as Expressions (Labeled Blocks)

const value = blk: {
    const tmp = compute();
    break :blk tmp * 2;          // `break :label value` yields from the block
};