Skip to content

Zig Booleans

A boolean is a value that’s either true or false. It’s the answer to a yes-or-no question. Is the user logged in? Is the list empty? Did the player win? Every if and every loop in your program runs on booleans, so they’re worth getting right. Zig’s booleans are simple, with one rule that’s stricter than Python, JavaScript or C: only a real bool counts as true or false.

The type is bool, and it has exactly two values, true and false:

const std = @import("std");
pub fn main() void {
const logged_in: bool = true;
const is_admin = false;
std.debug.print("logged in: {}, admin: {}\n", .{ logged_in, is_admin });
std.debug.print("type: {}\n", .{@TypeOf(is_admin)});
}

Output:

logged in: true, admin: false
type: bool

Print a bool with {} and you get the word true or false. Zig works out the type from the value, so const is_admin = false; is a bool without an annotation. Unlike numbers, a bool literal doesn’t need a fixed-size type for var either: var done = false; works, because there’s only one bool type.

Most booleans you’ll use don’t come from typing true. They come from comparing things:

const std = @import("std");
pub fn main() void {
const age: u32 = 17;
const cart_items: u32 = 0;
const is_adult = age >= 18;
const cart_empty = cart_items == 0;
std.debug.print("adult: {}, cart empty: {}\n", .{ is_adult, cart_empty });
}

Output:

adult: false, cart empty: true

Giving a condition a name, like is_adult, is a small habit that makes code much easier to read. Later if (is_adult) reads almost like English.

Zig combines booleans with the words and and or, and flips one with !:

Expression True when
a and b both a and b are true
a or b at least one of them is true
!a a is false
const std = @import("std");
pub fn main() void {
const has_ticket = true;
const age: u32 = 15;
const with_parent = true;
const can_enter = has_ticket and (age >= 16 or with_parent);
std.debug.print("can enter: {}\n", .{can_enter});
std.debug.print("needs a ticket: {}\n", .{!has_ticket});
}

Output:

can enter: true
needs a ticket: false

The visitor is too young on their own, but they’re with a parent, so the or part is true. They have a ticket too, so the whole thing is true.

and is applied before or, the same as in most languages, so a or b and c means a or (b and c). When you mix them, add parentheses like above. Nobody should have to remember the rule to read your code.

If you come from C, Java, JavaScript or Rust, you’ll type && sooner or later. Zig catches it and tells you what to write:

const std = @import("std");
pub fn main() void {
const a = true;
const b = false;
std.debug.print("{}\n", .{a && b});
}
main.zig:6:33: error: ambiguous use of '&&'; use 'and' for logical AND, or change whitespace to ' & &' for bitwise AND
std.debug.print("{}\n", .{a && b});
^

|| gives an error too, with the note '||' merges error sets; 'or' performs boolean OR. In Zig, || is used for something else entirely: combining two sets of errors, which you’ll meet in Zig Errors.

and and or stop as soon as they know the answer. With a and b, if a is false the whole thing is false, so b is never even looked at. With a or b, if a is true, b is skipped.

This is more than a speed trick. It lets the first check protect the second:

const std = @import("std");
pub fn main() void {
var total: u32 = 0;
var count: u32 = 0;
_ = &total;
_ = &count;
const busy = count != 0 and total / count > 5;
std.debug.print("busy: {}\n", .{busy});
}

Output:

busy: false

count is zero, so count != 0 is false and Zig never runs total / count. Swap the two sides and the program crashes, because dividing by zero is a bug. In a debug build you’ll see panic: division by zero. (_ = &total; keeps the values runtime-known; it’s explained in Zig Variables.)

In Python, JavaScript and C, you can write if (count) and a zero counts as false. Zig doesn’t allow it. A condition must be a real bool:

const std = @import("std");
pub fn main() void {
const unread: u32 = 3;
if (unread) {
std.debug.print("you have mail\n", .{});
}
}
main.zig:5:9: error: expected type 'bool', found 'u32'
if (unread) {
^~~~~~

Say what you mean instead: if (unread > 0) or if (unread != 0). The same goes for strings: there’s no “empty string is false”, you check name.len == 0. It’s a few more characters, but it removes a whole family of bugs, like 0 and "" being treated as “missing”.

Zig has no ? : operator, but if itself can give back a value. That’s handy for turning a bool into text:

const std = @import("std");
pub fn main() void {
const online = true;
const status = if (online) "online" else "offline";
std.debug.print("status: {s}\n", .{status});
}

Output:

status: online

You’ll see much more of if on the next page, Zig If…Else. Note there’s no need to write if (online == true). online already is the bool you’re testing.

A bool doesn’t convert to an integer on its own. When you want 1 for true and 0 for false, ask for it with @intFromBool. A common use is counting how many things are true:

const std = @import("std");
pub fn main() void {
const q1 = true;
const q2 = false;
const q3 = true;
var score: u32 = 0;
score += @intFromBool(q1);
score += @intFromBool(q2);
score += @intFromBool(q3);
std.debug.print("score: {d} of 3\n", .{score});
}

Output:

score: 2 of 3

Why not just add the three @intFromBool calls together? Try it and you’ll hit a surprise:

const std = @import("std");
pub fn main() void {
const q1 = true;
const q2 = false;
const q3 = true;
const score = @intFromBool(q1) + @intFromBool(q2) + @intFromBool(q3);
std.debug.print("score: {d} of 3\n", .{score});
}
main.zig:7:55: error: overflow of integer type 'u1' with value '2'
const score = @intFromBool(q1) + @intFromBool(q2) + @intFromBool(q3);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~

@intFromBool gives back a u1, a 1-bit integer that only holds 0 or 1. Adding two u1s gives another u1, and 2 doesn’t fit. Adding each one into a u32 like above fixes it, because a u1 turns into a u32 without any fuss. The reference entry for @intFromBool has the details.

Going the other way is just a comparison: const has_items = count != 0;. A bool takes one byte in memory.

A person can rent a car if they’re at least 21 and have a licence, or if they’re a staff member. Use const age: u32 = 19;, const has_licence = true; and const is_staff = true;, and print can rent: true.

Hint: put the and part in parentheses, then or it with is_staff.

Show solution
const std = @import("std");
pub fn main() void {
const age: u32 = 19;
const has_licence = true;
const is_staff = true;
const can_rent = (age >= 21 and has_licence) or is_staff;
std.debug.print("can rent: {}\n", .{can_rent});
}

Output:

can rent: true

The age check fails, so the part in parentheses is false, but is_staff is true, so or makes the whole thing true.

This doesn’t build. Make it print 3 items in the cart.

const std = @import("std");
pub fn main() void {
const items: u32 = 3;
if (items) {
std.debug.print("{d} items in the cart\n", .{items});
}
}

Hint: an if needs a real bool. What question are you actually asking about items?

Show solution
const std = @import("std");
pub fn main() void {
const items: u32 = 3;
if (items > 0) {
std.debug.print("{d} items in the cart\n", .{items});
}
}

Output:

3 items in the cart

items > 0 turns the number into the yes-or-no question you meant. items != 0 works just as well.

Three test results are true, true and false. Print passed 2, failed 1.

Hint: @intFromBool turns each one into 1 or 0. Add them into a u32, not straight into each other. Failed is 3 minus passed.

Show solution
const std = @import("std");
pub fn main() void {
const t1 = true;
const t2 = true;
const t3 = false;
var passed: u32 = 0;
passed += @intFromBool(t1);
passed += @intFromBool(t2);
passed += @intFromBool(t3);
std.debug.print("passed {d}, failed {d}\n", .{ passed, 3 - passed });
}

Output:

passed 2, failed 1

Each @intFromBool gives 1 for a pass, so passed ends up as the number of passes. Adding into a u32 avoids the u1 overflow from earlier.

  • A bool is true or false, and most come from comparisons like age >= 18.
  • Combine with the words and and or, flip with !. && and || are errors (|| merges error sets).
  • and and or short-circuit, so put the guard first: count != 0 and total / count > 5.
  • There are no truthy values: if (count) is an error. Write if (count != 0).
  • if (x) a else b gives back a value, which replaces the ternary operator.
  • @intFromBool turns a bool into 1 or 0, as a u1. Add it into a bigger integer.

Next up: Zig Strings, how text works when it’s really just bytes.

Quick check

1. What does if (count) do when count is a u32?
2. In count != 0 and total / count > 5, when is total / count evaluated?
3. Which is the logical OR in Zig?
4. Why does @intFromBool(a) + @intFromBool(b) + @intFromBool(c) fail when all three are true?