Nested conditions

for Zig 0.15.2 Buy

Nested conditions

        Another possible solution in this case is to use a nested if. Nested means we write one if inside another if. This way, we can also check one (or more) additional conditions that are not mutually exclusive with the first one:

better_score_error_2.zig

const std = @import("std");

const print = std.debug.print;

pub fn main() void {

   const n_record = 1200;

   const n_score = 5000;

   const n_maximum_score = 4000;

   if (n_record < n_score) {

      print("Your score {} is higher than the record ( {} )\n", .{ n_score, n_record });

      if (n_score > n_maximum_score) {

          print("Your score {} is impossible.\nYou cheated!\n", .{n_score});

      }

   } 

}

$ zig run better_score_error_2.zig

Your score 5000 is higher than the record (1200)

Your score 5000 is impossible.

You cheated!

We can nest as many if, if/else, or if/else if blocks as we want, but it’s not a recommended practice. It’s very easy to create real “code monsters” with too many nested conditions.

To keep the clean code and maintainable code, we can:

If what we want is to check multiple conditions in a single boolean expression, we can use boolean operators:

Table of boolean operators in Zig

and

Logical And 

True only if all conditions are true

true and false = false

or

Logical Or 

True if at least one condition is true

true or false = true

xor

Exclusive Or

True if exactly one condition is true, but not both

true xor true = false

true xor false = true

!

Negation (NOT)

Inverts the logical value

!true = false

!false = true

The most commonly used operators to combine boolean expressions are and, or, and !

Just like in math, operations inside parentheses take priority.

Let’s look at an example step by step:

true and !(true or false)  =

true and !(true) =

true and false =

false

If / Else if / Else
If / else that return values
© 2025 - 2026 Zen of Zig