Skip to content
LumenaryAcademy
Foundations 55 min

Values, types and control flow

Integers of any width, explicit conversions, arithmetic that never silently overflows, and if, switch, while and for as expressions.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Saying exactly what you mean

In many languages, a lot happens to numbers without your asking. C converts an int to unsigned in a comparison, silently wraps unsigned arithmetic, truncates a double assigned to an int, and leaves signed overflow undefined. JavaScript has one number type that is secretly a floating-point double. Python's integers grow without limit, which is convenient but means the size of every number is decided at run time.

Zig takes the opposite position: every number has a type whose size you choose, conversions that could lose information must be written down, and arithmetic that overflows is a bug the safe build modes catch, unless you use an operator that says "wrap" or "saturate". This can feel fussy for an afternoon. After that, it is a relief: when you read Zig code, there are no invisible conversions to worry about.

Control flow follows the same idea. if, switch, loops and blocks are expressions that produce values, switch must handle every case, and the few ways to leave a block are all keywords you can see.

DefinitionsH

Types and values

Definition— integer types

u followed by a bit width is an unsigned integer type and i a signed one: u8, i32, u64, but also u3 (0 to 7) or i7, any width up to 65535 bits. usize and isize are pointer-sized (64 bits on 64-bit systems) and are used for lengths and indices. C-compatible types such as c_int exist for talking to C. Integer literals may be written in hexadecimal (0xff), octal (0o17) or binary (0b1010), with underscores between digits for readability (8_200_000_000), and a character literal such as 'A' is simply the number 65.

Definition— comptime_int and comptime_float

The types of number literals like 10 and 2.5 before they are given a fixed type. They have unlimited precision and exist only at compile time. When a literal is assigned to a typed variable, the compiler checks that it fits: const x: u8 = 300; is a compile error.

Definition— const, var and undefined

const names a value that never changes; var a variable that may. Every variable must be initialised, but the initial value may be undefined, meaning "I will set this before reading it"; reading it before then is illegal behaviour, and debug builds fill it with a recognisable pattern to make such bugs visible.

Definition— coercion and explicit casts

A coercion is a conversion the compiler does automatically because it can never lose information: u8 to u32, u8 to i16, f32 to f64, and an integer to a float that can represent all of its values exactly (u16 or i32 to f64, but not i32 to f32 or u64 to f64). Every other conversion needs a builtin: @intCast (checked: illegal if the value does not fit), @truncate (keep the low bits on purpose), @floatFromInt, @intFromFloat, @floatCast. @as(T, x) asks for a coercion to T explicitly.

Definition— wrapping, saturating and checked arithmetic

+, - and * treat overflow as illegal behaviour. +%, -% and *% wrap around modulo 2 to the power of the width. +|, -| and *| saturate at the type's minimum or maximum. @addWithOverflow and its relatives return the wrapped result together with a bit that says whether overflow happened.

ComputationC

Numbers in practice

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

pub fn main() void {
    // Integers come in any width from 0 to 65535 bits, signed (i) or unsigned (u).
    const small: u8 = 255;
    const temperature: i16 = -40;
    const flags: u3 = 0b101; // three bits: 0 to 7
    const population: u64 = 8_200_000_000;
    std.debug.print("{d} {d} {d} {d}\n", .{ small, temperature, flags, population });
    std.debug.print("sizes in bytes: u8={d} i16={d} u64={d} usize={d}\n", .{ @sizeOf(u8), @sizeOf(i16), @sizeOf(u64), @sizeOf(usize) });

    // Widening is automatic; narrowing must be explicit.
    const wide: u32 = small; // u8 fits in u32: fine
    const back: u8 = @intCast(wide); // checked at run time in safe modes
    const low_byte: u8 = @truncate(@as(u32, 0x1234)); // keep the low 8 bits on purpose
    std.debug.print("{d} {d} 0x{x}\n", .{ wide, back, low_byte });

    // Overflow is illegal; ask for wrapping or saturation explicitly.
    var level: u8 = 250;
    level +%= 10; // wrapping: 260 mod 256
    const capped = @as(u8, 250) +| 10; // saturating: stops at 255
    const sum, const overflowed = @addWithOverflow(@as(u8, 250), 10);
    std.debug.print("wrap {d}, saturate {d}, checked {d} overflow={d}\n", .{ level, capped, sum, overflowed });

    // Floats, and conversions between integers and floats.
    const items: u32 = 7;
    const mean: f64 = @as(f64, @floatFromInt(items)) / 2.0;
    const rounded: u32 = @intFromFloat(@round(mean));
    std.debug.print("{d} {d}\n", .{ mean, rounded });

    // Signed division must say how to round.
    const a: i32 = -7;
    const b: i32 = 2;
    std.debug.print("trunc {d}, floor {d}, rem {d}, mod {d}\n", .{ @divTrunc(a, b), @divFloor(a, b), @rem(a, b), @mod(a, b) });
}
text
255 -40 5 8200000000
sizes in bytes: u8=1 i16=2 u64=8 usize=8
255 255 0x34
wrap 4, saturate 255, checked 4 overflow=1
3.5 4
trunc -3, floor -4, rem -1, mod 1

Line by line:

  • u3 holds 0b101 (5) in three bits. Odd widths are genuinely useful: protocol fields, packed flags and small enums are often 3, 5 or 12 bits wide, and the compiler range-checks them like any other integer.
  • const wide: u32 = small; needs no cast because every u8 fits in a u32. Going back needs @intCast, which in safe modes checks the value fits and panics if not. @truncate is for when you mean to throw the high bits away, as when extracting the low byte 0x34 from 0x1234. Notice that neither builtin names the target type: Zig takes it from the result location, the type of the variable being initialised. That is why @as appears where there is no such variable.
  • const sum, const overflowed = @addWithOverflow(...) uses destructuring: the builtin returns a tuple of the wrapped sum and a u1 overflow bit.
  • @floatFromInt converts the count to a float before dividing; @round then @intFromFloat converts back. In this case u32 would coerce to f64 on its own (every u32 value is exactly representable), but writing the conversion makes the intent obvious to readers.
  • For signed integers, / is not allowed at all on run-time values, because C and Python disagree about what -7 / 2 should be. You choose: @divTrunc rounds toward zero (C's behaviour, giving −3), @divFloor rounds down (Python's, giving −4). @rem and @mod are the matching remainders.

Example— Bits, shifts and a packed colour

Systems code often packs several small numbers into one integer. The RGB565 pixel format, common on small displays, stores red in 5 bits, green in 6 and blue in 5, in a single u16:

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

pub fn main() void {
    // A colour packed into 16 bits: 5 bits red, 6 green, 5 blue (RGB565).
    const red: u16 = 31;
    const green: u16 = 40;
    const blue: u16 = 12;
    const packed_colour: u16 = (red << 11) | (green << 5) | blue;
    const g: u6 = @truncate(packed_colour >> 5);
    var shift: u4 = 11;
    _ = &shift;
    std.debug.print("0x{x:0>4} green={d} red={d}\n", .{ packed_colour, g, packed_colour >> shift });
}
text
0xfd0c green=40 red=31

Zig adds a rule here that C does not have: the shift amount must have a type just wide enough to count the bits of the value being shifted. Shifting a u16 takes a u4 (0 to 15), and shifting a u8 takes a u3. A shift by 16 or more would be meaningless, and in C it is undefined behaviour; in Zig it cannot be expressed. Literal shift amounts like 11 are checked at compile time. A run-time shift amount of the wrong type is rejected:

text
main.zig:7:37: error: expected type 'u3', found 'u32'
    std.debug.print("{b}\n", .{x << n});
                                    ^
main.zig:7:37: note: unsigned 3-bit int cannot represent all possible unsigned 32-bit values

The fix is to make the amount the right type, usually with @intCast where it is computed. {b} prints binary and {x} hexadecimal, and {x:0>4} pads to four hex digits with zeros.

Note

Zig's floating-point types are f16, f32, f64, f80 and f128. They follow IEEE 754 like every mainstream language, so 0.1 + 0.2 is not exactly 0.3, and comparisons of computed floats should use a tolerance (std.math.approxEqAbs or approxEqRel) rather than ==. Division by zero on floats gives an infinity or NaN rather than a panic.

Worked examplesH

Control flow as expressions

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

fn grade(score: u8) u8 {
    return switch (score) {
        90...100 => 'A',
        80...89 => 'B',
        65...79 => 'C',
        0...64 => 'F',
        else => '?', // 101 to 255 are not valid scores
    };
}

pub fn main() void {
    // if is an expression.
    const hour: u8 = 15;
    const greeting = if (hour < 12) "good morning" else "good afternoon";
    std.debug.print("{s}\n", .{greeting});

    // switch must handle every possible value: here, with ranges and else.
    for ([_]u8{ 95, 82, 70, 40, 200 }) |s| {
        std.debug.print("{d}:{c} ", .{ s, grade(s) });
    }
    std.debug.print("\n", .{});

    // for over a range, and over an array with an index.
    const cities = [_][]const u8{ "Dakar", "Quito", "Hanoi" };
    for (cities, 0..) |city, i| {
        std.debug.print("{d}. {s}\n", .{ i + 1, city });
    }

    // Labeled loops: break out of the outer loop from the inner one.
    const target: u32 = 42;
    outer: for (1..10) |x| {
        for (1..10) |y| {
            if (x * y == target) {
                std.debug.print("{d} x {d} = {d}\n", .{ x, y, target });
                break :outer;
            }
        }
    }

    // A labeled block produces a value with break.
    const first_square_over_50 = blk: {
        var n: u32 = 1;
        while (n * n <= 50) n += 1;
        break :blk n * n;
    };
    std.debug.print("first square over 50: {d}\n", .{first_square_over_50});
}
text
good afternoon
95:A 82:B 70:C 40:F 200:? 
1. Dakar
2. Quito
3. Hanoi
6 x 7 = 42
first square over 50: 64
  • if produces a value. const greeting = if (hour < 12) "good morning" else "good afternoon"; replaces C's ?: operator. Conditions must be bool; Zig does not treat 0 or null as false.
  • switch is exhaustive. The compiler checks that every possible value of the operand is handled. A u8 has 256 possible values, so grade handles 0 to 100 with ranges and everything else with else. Leave out the else and the program does not compile. Ranges use three dots and include both ends: 90...100.
  • for iterates over arrays, slices and ranges. for (1..10) |x| counts from 1 to 9 (a range excludes its end); for (cities, 0..) |city, i| walks two sequences in step, the array and an open-ended counter, which is how you get an index. Zig has no C-style three-part for; use while with a continue expression.
  • Labels name loops and blocks. break :outer leaves the outer loop from inside the inner one. A labeled block blk: { ... break :blk value; } is an expression whose value is given by break, useful for computing a const with a few lines of logic. Loops are expressions too: a while or for may have an else branch, which runs when the loop ends without a break, so const found = for (items) |x| { if (x == target) break true; } else false; searches a list in one expression.

Example— A calendar calculation

Putting the pieces together: this program finds the day of the week for a date and counts leap years.

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

fn isLeapYear(year: u32) bool {
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0;
}

// Day of the week for a date in the Gregorian calendar (0 = Sunday),
// using a well-known method attributed to Tomohiko Sakamoto.
fn dayOfWeek(year: u32, month: u32, day: u32) u32 {
    const offsets = [_]u32{ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
    const y = if (month < 3) year - 1 else year;
    return (y + y / 4 - y / 100 + y / 400 + offsets[month - 1] + day) % 7;
}

fn dayName(d: u32) []const u8 {
    return switch (d) {
        0 => "Sunday",
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6 => "Saturday",
        else => unreachable, // the % 7 above makes this impossible
    };
}

pub fn main() void {
    const dates = [_][3]u32{ .{ 1969, 7, 20 }, .{ 2000, 1, 1 }, .{ 2026, 11, 19 } };
    for (dates) |date| {
        const d = dayOfWeek(date[0], date[1], date[2]);
        std.debug.print("{d}-{d:0>2}-{d:0>2} was a {s}\n", .{ date[0], date[1], date[2], dayName(d) });
    }
    var leap_count: u32 = 0;
    for (1900..2101) |year| {
        if (isLeapYear(@intCast(year))) leap_count += 1;
    }
    std.debug.print("leap years from 1900 to 2100: {d}\n", .{leap_count});
}
text
1969-07-20 was a Sunday
2000-01-01 was a Saturday
2026-11-19 was a Thursday
leap years from 1900 to 2100: 49

dayName ends its switch with else => unreachable. unreachable is a promise to the compiler that the branch cannot happen. In safe modes, reaching it anyway panics with "reached unreachable code"; in fast modes the optimiser assumes it never happens. It is the right tool here, because % 7 can only produce 0 to 6, and the wrong tool for anything that depends on input. The format specifier {d:0>2} pads with 0 to a width of two, aligned right. And @intCast(year) converts the usize that for (1900..2101) produces into the u32 that isLeapYear wants; it is checked, and will never fail for these values.

ExplanationH

Why Zig is strict about numbers

It is worth understanding the reasoning, because it will shape how you write Zig.

Every implicit conversion is a decision someone did not make. In C, comparing a signed and an unsigned value converts the signed one, so -1 < sizeof(x) is false. Code review cannot catch what is not written down. Zig moves those decisions into the code, as casts that a reviewer can see and question.

Overflow is usually a bug. Most programs never intend a counter to wrap around. Making ordinary + overflow illegal means safe builds find those bugs immediately, while +% documents the cases (hashes, checksums, ring buffers, random number generators) where wrapping is the point. Because the fast modes remove the checks, there is no run-time cost in the build you ship if you do not want one; many teams ship safe anyway.

Input needs handling, not panicking. The safety checks are for bugs. When a value comes from outside (a file, the network, a user), overflow is an expected possibility that the program must handle, and the standard library has functions that report it as an error instead: std.math.add(u32, a, b) returns either the sum or error.Overflow, and std.math.cast(u8, x) returns null when x does not fit, where @intCast would panic. The next lessons show how errors and optional values like these are handled.

Exhaustive switch turns future changes into compile errors. When a new case is added to an enum (the subject of the lesson after next), every switch that forgot it fails to compile, instead of silently falling through to a default.

Shadowing is not allowed. You cannot declare a local with the same name as another variable in an enclosing scope, so a name always means one thing within a function. The same goes for unused locals: the compiler is designed so that code says one thing clearly.

Common misconceptionsH

Common misconceptions

Misconception

"@intCast is like a C cast: it just reinterprets the bits." @intCast keeps the numeric value and is illegal if the value does not fit, checked in safe modes. Use @truncate to drop high bits deliberately and @bitCast to reinterpret bits between types of the same size, such as a u32 and an f32.

Misconception

"for (0..n) includes n." Ranges in for loops and slices exclude their end: 0..3 is 0, 1, 2. switch ranges are different, written with three dots and including both ends: 1...3 is 1, 2, 3.

Misconception

"I need a C-style for (i = 0; i < n; i += 2) loop." Zig's for only walks sequences and ranges. For any other stepping, use while with a continue expression: var i: usize = 0; while (i < n) : (i += 2) { ... }. It says the same thing with one more line.

Misconception

"undefined means zero." It means "no particular value". In debug builds Zig fills undefined memory with the byte 0xaa so that mistakes stand out, and in fast builds it may be anything. Never read a value before you have set it.

Misconception

"unreachable is a nicer way to write @panic." @panic("message") always panics, in every build mode. unreachable tells the optimiser that the code cannot run, so in the fast modes reaching it is undefined behaviour. Use unreachable only where you can prove it.

Exercises

Exercises

1. Values, types and control flow

CoreComputational

What does this program print?

const std = @import("std");

pub fn main() void {
    const a: i32 = -9;
    const b: i32 = 4;
    std.debug.print("{d} {d} {d}\n", .{ @divTrunc(a, b), @divFloor(a, b), @mod(a, b) });
}

2. Values, types and control flow

Warm-upComputational

What number does this print?

var x: u8 = 10;
x -%= 20;
std.debug.print("{d}\n", .{x});

3. Values, types and control flow

CoreComputational

What number does this program print?

var count: u32 = 0;
for (1..20) |n| {
    if (n % 3 == 0) continue;
    if (n > 10) break;
    count += 1;
}
std.debug.print("{d}\n", .{count});

4. Values, types and control flow

CoreComputational

What does this program print?

const std = @import("std");

pub fn main() void {
    const word = "kayak";
    const is_palindrome = blk: {
        var i: usize = 0;
        while (i < word.len / 2) : (i += 1) {
            if (word[i] != word[word.len - 1 - i]) break :blk false;
        }
        break :blk true;
    };
    const label = switch (word.len) {
        0 => "empty",
        1...4 => "short",
        else => "long",
    };
    std.debug.print("{} {s}\n", .{ is_palindrome, label });
}

5. Values, types and control flow

CoreHuman

a is a run-time variable of the first type. In which cases does const b: T = a; compile without a cast? Select all that apply.

Choose all that apply

6. Values, types and control flow

StretchHuman

x is a u32 and n is a u8 read from a file. Why does x << n fail to compile, and what is the best fix?

Choose one

Further reading and resources