TExcelTAD
Home › Zig › Zig If..Else

Zig If..Else

if runs code only when a condition is true. In Zig, if is also an expression that produces a value, and it has special forms for optionals and errors that you will use constantly later in the course.

Basic if, else if, else

zig · try it yourself
const std = @import("std");

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

    if (temperature > 30) {
        std.debug.print("Hot\n", .{});
    } else if (temperature > 20) {
        std.debug.print("Warm\n", .{});
    } else {
        std.debug.print("Cool\n", .{});
    }
}
Warm

The condition must be a bool — Zig has no "truthy" numbers or pointers. Parentheses around the condition are required; braces are optional for a single statement but recommended.

if as an expression

Because if returns a value, it replaces C's ternary operator ?::

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const items: u32 = 1;
    const word = if (items == 1) "item" else "items";
    std.debug.print("{d} {s}\n", .{ items, word });

    const score: u32 = 73;
    const grade: u8 = if (score >= 90) 'A' else if (score >= 70) 'B' else 'C';
    std.debug.print("grade {c}\n", .{grade});

    const shipping: f64 = if (score > 50) 0 else 4.99;
    std.debug.print("shipping {d}\n", .{shipping});
}
1 item
grade B
shipping 0

Change items to 3 and run it again to see the other branch chosen.

When used as an expression, an if must have an else, because the expression must produce a value in every case.

Capturing optionals

An optional (?T) either holds a value or is null. if can test it and unwrap the value in one step — the |name| part is called a capture:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const names = [_][]const u8{ "Ana", "Binh", "Chloe" };
    const found: ?usize = for (names, 0..) |n, i| {
        if (std.mem.eql(u8, n, "Binh")) break i;
    } else null;

    if (found) |index| {
        std.debug.print("found at index {d}\n", .{index});
    } else {
        std.debug.print("not found\n", .{});
    }
}
found at index 1

Inside the first branch, index is a plain usize — no null check needed. The Optionals lesson covers this in depth.

Capturing errors

Similarly, an error union (E!T) can be split into the success value and the error:

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const inputs = [_][]const u8{ "42", "4x2" };
    for (inputs) |text| {
        if (std.fmt.parseInt(i32, text, 10)) |value| {
            std.debug.print("'{s}' -> {d}\n", .{ text, value });
        } else |err| {
            std.debug.print("'{s}' -> error {t}\n", .{ text, err });
        }
    }
}
'42' -> 42
'4x2' -> error InvalidCharacter

Summary of forms

Form Runs when
if (cond) { … } cond is true
if (opt) |v| { … } else { … } opt is not null; v is the value
if (result) |v| { … } else |err| { … } no error / an error occurred
const x = if (c) a else b; expression form; else required

Tip: Keep conditions readable by naming them: const is_weekend = day == .sat or day == .sun; then if (is_weekend) ….

Test yourself

What replaces C's cond ? a : b in Zig?

  1. cond ?? a : b
  2. if (cond) a else b
  3. select(cond, a, b)
  4. a if cond else b

In if (maybe) |v| { … }, what is v?

  1. A boolean
  2. The unwrapped value of the optional
  3. A pointer to maybe
  4. The error code

Why must an if expression used as a value have an else?

  1. Style rule only
  2. The expression must produce a value in every case
  3. To avoid a runtime panic
  4. It doesn't need one