If Statements
if is the simplest form of control flow:
const std = @import("std");
const print = std.debug.print;
pub fn main() void {
var a: i64 = 2;
if (a < 3) {
print("{} < {}\n", .{ a, 3 });
a = -a;
}
// In simple cases, we can leave out the { and }.
if (a < 3)
print("{} < {}\n", .{ a, 3 });
// But we need them when there’s an 'else' clause.
if (a > 0) {
print("{} is positive\n", .{a});
} else if (a == 0) {
print("{} is zero\n", .{a});
} else {
print("{} is negative\n", .{a});
}
// We can also use 'if' as an expression.
const b = if (a > 0) a else -a;
print("b = {}\n", .{b});
}$ zig run if.zig
2 < 3
-2 < 3
-2 is negative
b = 2
Next example: Switch Statements.