Card 1 / 11
In Zig, if is an expression that returns a value. You can use it directly in a return statement.
Comparison operators: >, <, >=, <=, ==, !=
const x = if (a > b) a else b;a |
b |
result |
|---|---|---|
10 |
5 |
10 |
3 |
9 |
9 |
7 |
7 |
7 |
-2 |
-5 |
-2 |
return if (a > b) a else b; returns the maximum.
/// Return the larger of the two numbers
fn max(a: i32, b: i32) i32 {
return if (a > b) a else b;
}Card 2 / 11
Use an if expression to check whether a number is negative and negate it if so.
The negation operator on integers is just a minus sign: -x.
x |
result |
|---|---|
5 |
5 |
-3 |
3 |
0 |
0 |