Booleans
A boolean value is either true or false.
Booleans
A boolean value is either true or false.
const ready: bool = true;
const done: bool = false;
The type is bool.
Boolean values are used in conditions.
const std = @import("std");
pub fn main() void {
const ready = true;
if (ready) {
std.debug.print("ready\n", .{});
}
}
The condition of an if must be a boolean.
const n = 1;
if (n) { // error
// ...
}
Zig does not treat integers as booleans. Use an explicit comparison.
const n = 1;
if (n != 0) {
// ...
}
Comparison operators produce boolean values.
const a = 10;
const b = 20;
const less = a < b;
const same = a == b;
Common comparison operators are:
| Operator | Meaning |
|---|---|
== |
equal |
!= |
not equal |
< |
less than |
<= |
less than or equal |
> |
greater than |
>= |
greater than or equal |
Boolean operators combine boolean values.
const ok = true;
const valid = false;
const both = ok and valid;
const either = ok or valid;
const opposite = !ok;
and is true only when both operands are true.
or is true when at least one operand is true.
! changes true to false and false to true.
Boolean operators short-circuit.
if (index < data.len and data[index] == 0) {
// safe
}
The second expression is evaluated only if the first expression is true. If index is not less than data.len, data[index] is not evaluated.
This matters for bounds checks, null checks, and error checks.
if (ptr != null and ptr.?.* == 10) {
// ptr is not null before it is unwrapped
}
A boolean value may be returned from a function.
fn isEven(n: i32) bool {
return @mod(n, 2) == 0;
}
Then it may be used directly in a condition.
if (isEven(10)) {
std.debug.print("even\n", .{});
}
A boolean should describe a fact.
const is_empty = len == 0;
const has_space = used < capacity;
const is_open = true;
Good boolean names usually read well inside an if.
if (has_space) {
// add another item
}
A boolean value can be printed with {}.
const std = @import("std");
pub fn main() void {
const enabled = true;
std.debug.print("{}\n", .{enabled});
}
The output is:
true
Use booleans for decisions. Use integers for counts and sizes. Do not mix the two.
Exercises:
-
Declare a boolean named
readyand print it. -
Write a function
isPositivethat takes ani32and returnstrueif the number is greater than zero. -
Write a condition that checks whether
nis between1and10, inclusive. -
Write a condition that checks whether an array index is in bounds before reading the array.
-
Replace an integer used as a flag with a
bool.