🎓 A1Learner
🔍
0 of 55 lessons completed

Zig If Else

An if statement runs a block of code only when a condition is true. Add else to run a different block when the condition is false.

The if block runs when the condition is true

The score is 82 and the pass mark is 60. The condition is true, so the block runs and prints its word.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const score: i32 = 82;
    if (score >= 60) {
        try out.print("pass\n", .{});
    }
}

The else block runs when the condition is false

This time the score is 35, below the pass mark. The if block is skipped and the else block runs instead.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const score: i32 = 35;
    if (score >= 60) {
        try out.print("pass\n", .{});
    } else {
        try out.print("fail\n", .{});
    }
}

An if expression stores one of two values

An if can work as an expression that picks a value. Here it picks a letter and that letter is stored in mark.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const score: i32 = 82;
    const mark: u8 = if (score >= 60) 'P' else 'F';
    try out.print("{c}\n", .{mark});
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const score: i32 = 74;
    const grade: u8 = if (score >= 90) 'A' else if (score >= 70) 'B' else if (score >= 60) 'C' else 'F';
    try out.print("score: {d}\n", .{score});
    try out.print("grade: {c}\n", .{grade});
}

Key points

  • Condition: an if condition is a bool value written in parentheses.
  • True branch: the block after if runs when the condition is true.
  • Else branch: the block after else runs when the condition is false.
  • Else if: an extra if placed in the else branch tests another condition in order.
  • Expression: an if can produce a value, so one of two values can be stored in a const.

In this example, the score is 74. The first test fails because 74 is below 90, and the second test passes because 74 reaches 70, so grade stores B and every later branch is skipped.

Note

Zig has no truthy numbers, so the condition must be a bool and not 1 or 0.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A program sets age to 15 and runs if (age >= 18) to print "adult", with an else that prints "teen". What does the program print?