CHAPTER 2
Decisions
In programs, it’s very common to face the need to make decisions. Basically, it comes down to asking: what path should my program take if a certain condition is met?
Let’s imagine the flow of a simple program like the ones we’ve written so far represented as a straight line (a single path):
|
Start of the program |
pub fn main() void { … |
|
|
|
const n_a = 2 + 1; print("\n{}:", .{n_a});
… |
|
|
End of the program |
} |
But what if we need to run a block of code only when a certain condition is met? As an example, imagine a user has played two rounds of the same video game. If the second score is higher than the first, we want to print a congratulatory message:
better.zig |
|
const std = @import("std"); const print = std.debug.print; pub fn main() void { const n_record = 1200; const n_score = 3000; if (n_score > n_record) { print("Congratulations! You've beaten the high score.\n", .{}); }
} |
|
$ zig run better.zig |
|
Congratulations! You've beaten the high score. |
Comparison - Boolean expressions and operators
In the previous example, you’ll see the symbol “>” which means “greater than”. This works just like in math.
These kinds of symbols are called “comparison operators”. Evaluating a comparison operator always returns a boolean: either true or false.
In Zig, we have the following operators:
|
== |
Equal to |
3 == 3 |
|
!= |
Not equal to |
3 != 4 |
|
> |
Greater than |
7 > 2 |
|
< |
Less than |
2 < 7 |
|
>= |
Greater or equal |
5 >= 5 |
|
<= |
Less or equal |
4 <= 5 |
Look at the third column of the previous table and see if you can tell which expressions evaluate to true.
