Zig Comparison Operators
A comparison operator compares two values and gives a bool result, true or false.
Equality checks give true or false
The == operator compares for sameness. The != operator compares for difference.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{}\n", .{5 == 5});
try out.print("{}\n", .{5 == 6});
try out.print("{}\n", .{5 != 6});
}Ordering checks compare size
The < operator checks smaller. The > operator checks bigger.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{}\n", .{3 < 7});
try out.print("{}\n", .{7 < 3});
try out.print("{}\n", .{9 > 4});
}Inclusive checks allow equality
The <= and >= operators pass when the values are equal too.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{}\n", .{5 <= 5});
try out.print("{}\n", .{4 >= 5});
try out.print("{}\n", .{6 >= 6});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const score = 72;
const pass_mark = 50;
const top_score = 90;
try out.print("{}\n", .{score > pass_mark});
try out.print("{}\n", .{score == top_score});
try out.print("{}\n", .{score >= pass_mark});
}Key points
- Equal: the == operator checks whether two values are the same.
- Not equal: the != operator checks whether two values are different.
- Less than: the < operator checks whether the first value is smaller.
- Greater than: the > operator checks whether the first value is bigger.
- Inclusive checks: <= means less than or equal, and >= means greater than or equal.
- Result: every comparison gives a bool, either true or false.
In this example, the score 72 is greater than the pass mark 50, so the first check prints true. The score does not equal the top score 90, so the second check prints false. The last check prints true because 72 is greater than or equal to 50.
Note
Zig uses == for comparing, while a single = stores a value in a binding.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A value x holds 8. Which comparison gives true?