Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Control Flow and Functions

if and switch

Learn Zig conditionals: if as an expression, else if chains, unwrapping optionals with if, switch with ranges, multiple values, captures, exhaustiveness, else and labeled switch.

Branching in Zig looks familiar, with two twists that matter. First, both if and switch are expressions: they produce a value, so you rarely need a temporary variable. Second, switch must be exhaustive: the compiler rejects a switch that forgets a case. Together these remove a lot of boilerplate and a lot of bugs.

if, else if, else

The condition must be a bool (or an optional or error union, shown later). Parentheses around it are required; braces are required unless the body is a single expression or statement on the same line.

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

pub fn main() void {
    const temperature: i32 = 24;

    if (temperature < 0) {
        std.debug.print("freezing\n", .{});
    } else if (temperature < 20) {
        std.debug.print("cool\n", .{});
    } else {
        std.debug.print("warm\n", .{});
    }
}

Output: warm.

if as an expression

Because if yields a value, it replaces the ternary operator ?:. Both branches must produce the same type, and the else is mandatory:

ZIG
const label = if (temperature >= 20) "warm" else "cool";
const abs_value = if (temperature < 0) -temperature else temperature;

There is no truthiness: if (temperature) is an error. Compare explicitly.

Unwrapping with if

When the thing being tested is an optional (?T), the |value| capture gives you the unwrapped value inside the block:

ZIG
const maybe_port: ?u16 = 8080;

if (maybe_port) |port| {
    std.debug.print("listening on {d}\n", .{port});
} else {
    std.debug.print("no port configured\n", .{});
}

The same shape works for error unions: if (parse()) |value| {...} else |err| {...}. Optionals and errors have their own lessons.

switch

switch compares one value against several prongs. Each prong is pattern => expression,. There is no fallthrough and no break, so you cannot forget it.

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

pub fn main() void {
    const day: u8 = 6;

    const kind = switch (day) {
        1, 7 => "weekend",           // several values
        2...6 => "weekday",          // inclusive range
        else => "invalid",           // everything else
    };

    std.debug.print("day {d} is a {s}\n", .{ day, kind });
}

Output: day 6 is a weekday.

Patterns can be:

  • a single value: 5 =>
  • a list: 1, 3, 5 =>
  • an inclusive range: 10...19 => (note three dots)
  • an enum or error name: .red =>
  • a combination with inline and captures (see below)

Exhaustiveness

Integers have too many values to list, so you need an else prong. Enums and booleans do not: you list every case, and if you add a new enum value later, the compiler points at every switch that must handle it.

ZIG
const Color = enum { red, green, blue };

fn describe(c: Color) []const u8 {
    return switch (c) {
        .red => "warm",
        .green => "natural",
        .blue => "cool",
    };
}

Adding yellow to Color produces: error: switch must handle all possibilities. Resist the urge to add else to enum switches: it turns that helpful error into silence.

Blocks and unreachable

A prong can run several statements with a block:

ZIG
switch (code) {
    0 => std.debug.print("ok\n", .{}),
    1...9 => {
        std.debug.print("warning {d}\n", .{code});
    },
    else => unreachable,   // "this cannot happen": panics in safe modes
}

unreachable is a promise to the compiler. In Debug and ReleaseSafe it panics if reached; in release-fast modes reaching it is undefined behavior, so use it only for truly impossible cases.

Captures: switching on unions

Tagged unions carry data. switch extracts it with a capture:

ZIG
const Shape = union(enum) {
    circle: f64,                       // radius
    rectangle: struct { w: f64, h: f64 },
    point,
};

fn area(s: Shape) f64 {
    return switch (s) {
        .circle => |r| 3.14159 * r * r,
        .rectangle => |rect| rect.w * rect.h,
        .point => 0,
    };
}

Unions are covered in the Types and Memory chapter; the key point is that switch and captures work together.

Labeled switch

Newer versions of Zig let a switch loop on itself, which is excellent for state machines and interpreters. The label names the switch, and continue :label new_value re-dispatches with a new value:

ZIG
sw: switch (@as(u8, 0)) {
    0 => continue :sw 1,
    1 => continue :sw 2,
    2 => std.debug.print("reached 2\n", .{}),
    else => unreachable,
}

The compiler turns this into direct jumps, so it is also faster than a loop around a switch. It was added in Zig 0.14.

Flow with and, or and early returns

Beyond if and switch, most branching in real code is early return to avoid deep nesting:

ZIG
fn describeAge(age: i32) []const u8 {
    if (age < 0) return "invalid";
    if (age < 13) return "child";
    if (age < 20) return "teenager";
    return "adult";
}

Stand-ins you can run

The switch with ranges and an expression result maps to Rust's match, which is also exhaustive.

Rust Stand-in (Rust): match as an exhaustive expression

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.

C's switch has fallthrough, which Zig removes. This stand-in shows the classic bug in action:

C Stand-in (C): fallthrough, the bug Zig prevents

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is Zig's equivalent of the ternary operator?

    if is an expression, so it can appear on the right side of a declaration.
  2. 2. How do you write an inclusive range prong that matches 2 through 6?

    Switch ranges use three dots and include both ends.
  3. 3. What happens if a switch on an enum misses a case and has no else?

    Switches must be exhaustive, so the compiler requires every enum value to be handled.
  4. 4. What does if (maybe) |value| { ... } do?

    The capture unwraps the optional inside the block.
  5. 5. Does Zig's switch fall through to the next prong?

    There is no fallthrough and no break in switch prongs.

Summary

  • if and switch are expressions; the conditions must be bool (or optional / error union).
  • if (opt) |v| unwraps an optional; else handles the empty case.
  • switch supports lists, inclusive ranges (a...b), captures, blocks and else; it never falls through.
  • Enum switches must list every case, so avoid else there.
  • A labeled switch with continue :label builds state machines.

Next: Loops