If / Else

for Zig 0.15.2 Buy

If / Else

If we want something to run after the if, regardless of the evaluated condition, we just place it outside the block enclosed by braces. And if we want to run a block of code only when the if condition is not met, that is when it returns false, then we need to add an else { } block afterwards.


if (Boolean expression){

    The code inside this block runs only if the boolean expression returns true

} else {

   The code inside this block runs if the boolean expression returns false

}


The program flow with an if / else covers both possible cases:

Start of the program

pub fn main() void { …

const n_a = 2 + 1;

if (n_a > 3) {

 print("n_a is greater than 3", .{});

} else {

 print("n_a is not greater than 3", .{});

}

   

 …

End of the program

}

After that split, the program’s path comes back together.

Let’s expand the previous example by adding an else block to show an encouraging message in case the player didn’t beat the previous time:

better_time_2.zig

const std = @import("std");

const print = std.debug.print;

pub fn main() void {

    const n_time_record = 10.0;

    const n_time = 11.0;

    if (n_time < n_time_record) {

      print("Congratulations! With your time: {}, you’ve beaten the previous record ({}).\n", .{ n_time, n_time_record });

    } else {

      print("Keep trying. Your time: {} is worse than the previous record ({}).\n", .{ n_time, n_time_record });

    }

 

}

$ zig run better_time_2.zig

Keep trying. Your time: 11 is worse than the previous record (10).

At this point you’re probably wondering: what if I want to run a block of code when the first condition isn’t met, but I still want to check whether a second condition is true?

If
If / Else if / Else
© 2025 - 2026 Zen of Zig