Learn/Zig/4. Making decisions
Lesson 4 of 8
Sign in

Zig, lesson 4

Making decisions

Programs constantly choose: is the password long enough, did the player win, is it a weekend? Zig's tools for this are if and switch.

Comparisons and boolean operators

OperatorMeaning
== / !=equal / not equal
<, <=, >, >=ordering

2 exercises to try what you just read.

Exercise 1

Letter grade

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

and, or
combine two bools (short-circuit)
!not

A condition must be a real bool. Zig will not treat 0 or an empty string as false; write the comparison out, like count == 0.

Strings are slices, so == would compare their addresses, not their letters. Compare text with std.mem.eql(u8, a, b).

if and else

The condition goes in parentheses, and the bodies in braces. Zig checks the branches in order and runs only the first one whose condition is true.

if as an expression

if also produces a value, which removes the need for a separate variable that you fill in later:

Both branches must produce compatible types, and the else is required, because the expression always needs a value.

switch

switch picks a branch based on one value. Each prong lists values, separated by commas, or an inclusive range written with three dots:

A switch must be exhaustive: every possible value of the type needs a prong. For integers that almost always means an else at the end. The compiler checks this, so you can't forget a case by accident. Like if, switch is an expression; note the semicolon after the closing brace when you assign it.

A prong can also run a block of statements:

else => {} means "do nothing for everything else".

Further reading

  • Zig Language Reference: if
  • Zig Language Reference: switch
  • Standard library: std.mem.eql

Read a test score and print its letter grade:

  • 90 to 100: A
  • 80 to 89: B
  • 70 to 79: C
  • 60 to 69: D
  • 0 to 59: F
  • below 0 or above 100: Invalid

Input: one line with a whole number (it can be negative, so the starter uses i64). Output: the grade on one line. For 85, print B. A switch with ranges fits this perfectly.

A year is a leap year if it is divisible by 4, except years divisible by 100, which are not, unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.

Input: one line with a year (a positive number, so the starter uses u64 and % works). Output: leap or common.

const temp: i64 = 31;
if (temp > 25) {
    try out.print("It's hot!\n", .{});
} else if (temp > 15) {
    try out.print("It's mild.\n", .{});
} else {
    try out.print("Bring a jacket.\n", .{});
}
const advice = if (temp > 25) "Wear a hat" else "Bring a jacket";
const dice: u8 = 4;
const label = switch (dice) {
    1 => "Ouch",
    2, 3 => "Meh",
    4...6 => "Nice roll",
    else => "That's not a die",
};
switch (dice) {
    6 => {
        try out.print("Bonus turn!\n", .{});
    },
    else => {},
}