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 elseThe 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 expressionif 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.
switchswitch 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".
Read a test score and print its letter grade:
90 to 100: A80 to 89: B70 to 79: C60 to 69: D0 to 59: F0 or above 100: InvalidInput: 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 => {},
}