Skip to content

Zig If...Else

Most programs need to make choices: print a warning if the disk is full, charge less if the customer is a child, stop if the input is empty. In Zig you make those choices with if and else. They look a lot like C or JavaScript, with two twists that catch newcomers: the condition must be a real bool, and if can hand back a value, which is how Zig gets by without a ? : operator.

An if runs a block of code only when its condition is true. The condition goes in parentheses, and the code goes in curly braces:

const std = @import("std");
pub fn main() void {
const temperature: i32 = 31;
if (temperature > 25) {
std.debug.print("It's hot today.\n", .{});
}
std.debug.print("Done checking.\n", .{});
}

Output:

It's hot today.
Done checking.

temperature > 25 is true, so the first print runs. The last line runs either way, because it’s outside the if block. The parentheses around the condition are required in Zig, just like in C.

else gives you a second path for when the condition is false. else if lets you check more conditions in order, and Zig stops at the first one that’s true:

const std = @import("std");
fn describe(temperature: i32) void {
if (temperature > 25) {
std.debug.print("{d}: hot\n", .{temperature});
} else if (temperature > 10) {
std.debug.print("{d}: mild\n", .{temperature});
} else {
std.debug.print("{d}: cold\n", .{temperature});
}
}
pub fn main() void {
describe(31);
describe(18);
describe(-4);
}

Output:

31: hot
18: mild
-4: cold

fn describe(temperature: i32) void is a small function that takes a number and prints something. You’ll learn functions properly in Zig Functions; here it just lets us try three values without repeating the whole if.

Look at 18: it’s not above 25, so Zig moves on to else if (temperature > 10), which is true, and prints “mild”. It never looks at the else. For -4, both checks fail, so the else block runs.

In C, Python and JavaScript, if (count) works with a number: zero means false, anything else means true. Zig doesn’t do that. The condition has to be a bool (true or false), and anything else is a compile error:

const std = @import("std");
pub fn main() void {
const count = 5;
if (count) {
std.debug.print("We have some.\n", .{});
}
}
main.zig:6:9: error: expected type 'bool', found 'comptime_int'
if (count) {
^~~~~

The fix is to say what you mean with a comparison:

const std = @import("std");
pub fn main() void {
const count = 5;
if (count != 0) {
std.debug.print("We have some.\n", .{});
}
}

Output:

We have some.

This rule feels strict for a day, then you stop noticing it. It also means you’ll never be bitten by C’s classic typo if (x = 5): in Zig, assignment isn’t an expression, so that line doesn’t compile. You can combine conditions with and, or and !, which you met in Zig Booleans.

Here’s the part that’s new if you come from C or JavaScript. In Zig, if isn’t only a statement, it’s also an expression: it can produce a value. You write the value of each branch without braces, and you can store the result:

const std = @import("std");
pub fn main() void {
const age: u8 = 15;
const label = if (age >= 18) "adult" else "minor";
const price: u32 = if (age < 12) 5 else 8;
std.debug.print("{s}, ticket costs {d}\n", .{ label, price });
}

Output:

minor, ticket costs 8

Read if (age >= 18) "adult" else "minor" as “if the age is at least 18, the value is "adult", otherwise "minor"”. This is what C and JavaScript do with age >= 18 ? "adult" : "minor", and what Python does with "adult" if age >= 18 else "minor". Zig has no ? : operator because if already does the job.

You can chain else if in an expression too:

const std = @import("std");
fn grade(score: u8) u8 {
return if (score >= 90) 'A' else if (score >= 70) 'B' else if (score >= 50) 'C' else 'F';
}
pub fn main() void {
std.debug.print("{c} {c} {c} {c}\n", .{ grade(95), grade(72), grade(55), grade(12) });
}

Output:

A B C F

return if (...) ... else ...; hands the value of the whole if back to the caller. {c} prints a u8 as a character. Past three or four branches this gets hard to read, and a switch is usually the nicer tool.

1. Forgetting the else. An if expression needs a value on every path. Without else, the “false” path has no value (its type is void), and the two types don’t match:

const std = @import("std");
fn sign(n: i32) []const u8 {
const word = if (n > 0) "positive";
return word;
}
pub fn main() void {
std.debug.print("{s}\n", .{sign(4)});
}
main.zig:4:18: error: incompatible types: '*const [8:0]u8' and 'void'
const word = if (n > 0) "positive";
^~~~~~~~~~~~~~~~~~~~~

The fix is to add else with a value of the same kind: if (n > 0) "positive" else "not positive".

2. Plain numbers with no type. When the condition is only known while the program runs, Zig needs to know which number type the result has. A bare 5 or 8 has the compile-time-only type comptime_int, so this fails:

const std = @import("std");
fn ticketPrice(age: u8) u32 {
const price = if (age < 12) 5 else 8;
return price;
}
pub fn main() void {
std.debug.print("{d}\n", .{ticketPrice(30)});
}
main.zig:4:19: error: value with comptime-only type 'comptime_int' depends on runtime control flow
const price = if (age < 12) 5 else 8;
^~~~~~~~~~~~~~~~~~~~~~
main.zig:4:27: note: runtime control flow here
const price = if (age < 12) 5 else 8;
~~~~^~~~

The error sounds scary, but the fix is small: give the result a type, const price: u32 = if (age < 12) 5 else 8;. Returning the if directly (return if (age < 12) 5 else 8;) also works, because the function’s return type tells Zig what type to use. In the earlier example age was a const known while compiling, which is why it worked without trouble.

If a branch is a single statement, you can leave out the braces:

const std = @import("std");
pub fn main() void {
const items: u32 = 0;
if (items == 0) std.debug.print("The cart is empty.\n", .{});
if (items > 0) std.debug.print("Ready to pay.\n", .{}) else std.debug.print("Add something first.\n", .{});
}

Output:

The cart is empty.
Add something first.

This is handy for one-liners like an early return. For anything longer, use braces: they make it obvious where each branch ends.

Zig has two special kinds of values that if knows how to open up. An optional (?u32) holds a value or null, and an error union (anyerror!u32) holds a value or an error. if can check them and give you the value inside, using |name|. This is called a capture:

const std = @import("std");
pub fn main() void {
const maybe_age: ?u32 = 42;
if (maybe_age) |age| {
std.debug.print("Age is {d}\n", .{age});
} else {
std.debug.print("No age given\n", .{});
}
const result: anyerror!u32 = error.NotFound;
if (result) |value| {
std.debug.print("Got {d}\n", .{value});
} else |err| {
std.debug.print("Failed: {s}\n", .{@errorName(err)});
}
}

Output:

Age is 42
Failed: NotFound

In the first if, maybe_age isn’t null, so the value 42 is captured as age. In the second, result holds an error, so the else |err| branch runs and err is that error. @errorName turns an error into its name as text.

Don’t worry about the details yet. You’ll use these all the time once you meet Zig Optionals and Zig Try & Catch. For now, remember the shape: if (x) |value| { ... }. The language reference on if shows every form in one place.

Write a program that checks a number and prints 7 is odd or 10 is even. Try it with both numbers.

Hint: n % 2 == 0 is true for even numbers. A small function lets you test both values.

Show solution
const std = @import("std");
fn check(n: u32) void {
if (n % 2 == 0) {
std.debug.print("{d} is even\n", .{n});
} else {
std.debug.print("{d} is odd\n", .{n});
}
}
pub fn main() void {
check(7);
check(10);
}

Output:

7 is odd
10 is even

% gives the remainder after dividing. Even numbers leave no remainder when divided by 2.

This code works in C, but not in Zig. Fix it so it prints Lives left: 3.

const std = @import("std");
pub fn main() void {
const lives: u8 = 3;
if (lives) {
std.debug.print("Lives left: {d}\n", .{lives});
} else {
std.debug.print("Game over\n", .{});
}
}

Hint: Zig wants a bool. What are you really asking about lives?

Show solution
const std = @import("std");
pub fn main() void {
const lives: u8 = 3;
if (lives > 0) {
std.debug.print("Lives left: {d}\n", .{lives});
} else {
std.debug.print("Game over\n", .{});
}
}

Output:

Lives left: 3

if (lives) asks Zig to treat a number as true or false, which it won’t do. lives > 0 is a real bool.

Orders of 50 or more ship for free; smaller orders cost 4. Write fn shipping(total: u32) u32 that returns the cost with a single if expression, then print the cost for 30 and 75.

Hint: return if (...) 0 else 4;

Show solution
const std = @import("std");
fn shipping(total: u32) u32 {
return if (total >= 50) 0 else 4;
}
pub fn main() void {
std.debug.print("Order 30: shipping {d}\n", .{shipping(30)});
std.debug.print("Order 75: shipping {d}\n", .{shipping(75)});
}

Output:

Order 30: shipping 4
Order 75: shipping 0

The function’s return type u32 tells Zig what type the 0 and 4 should be, so no extra annotation is needed.

  • if (condition) { ... } else if (...) { ... } else { ... } runs the first branch whose condition is true.
  • The condition must be a bool. Zig never treats numbers or pointers as true or false.
  • if is also an expression: const x = if (a) 1 else 2;. That’s Zig’s version of ? :.
  • An if expression needs an else, and number results need a type when the condition is only known at run time.
  • Braces are optional for single statements, but use them for anything longer.
  • if (x) |value| captures the value inside an optional or error union (more in later lessons).

Next up: Zig Switch, for when one value can lead to many different paths.

Quick check

1. What happens with const n: u32 = 3; if (n) { ... } in Zig?
2. How do you write C's x > 0 ? 1 : -1 in Zig?
3. Why does const word = if (n > 0) "yes"; fail to compile?
4. In if (maybe) |v| { ... }, what is v?