Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 37 ยท Language Basics

Booleans and Operators

Learn Zig's bool type and every operator: arithmetic, comparison, and/or/not as words, bitwise and shift operators, compound assignment, precedence and common pitfalls.

Zig's operators are small in number and strict in meaning. The most visible difference from C is that logic uses words (and, or, !) while bitwise work uses symbols, and that conditions must be real booleans: there is no "zero is false". This lesson lists every operator you need and the traps that go with them.

The bool type

bool has exactly two values, true and false. Comparison operators produce a bool, and if and while accept only a bool (or an optional or error union, which come later). Writing if (count) with an integer is a compile error; write if (count != 0).

ZIG
const std = @import("std");

pub fn main() void {
    const age: u8 = 20;
    const has_ticket = true;

    const adult = age >= 18;
    const can_enter = adult and has_ticket;
    const needs_help = !has_ticket or age < 12;

    std.debug.print("{} {} {}\n", .{ adult, can_enter, needs_help });
}
TEXT
true true false

and and or short-circuit: the right side is evaluated only when needed. Unlike C there is no &&, || or implicit conversion of numbers to bool.

Comparison operators

==, !=, <, <=, >, >=. They work on numbers, bools, enums and pointers. You cannot compare strings (byte slices) with ==; that would compare pointers and lengths, so the compiler rejects it. Use std.mem.eql(u8, a, b) instead (next lessons).

Arithmetic operators

Operator Meaning Notes
+ - * add, subtract, multiply overflow is checked in safe modes
/ divide for signed integers use @divTrunc etc.
% remainder unsigned only; signed uses @mod / @rem
+% -% *% wrapping modular arithmetic
`+ - *
-x negate -%x wraps for the minimum value
++ array concatenation compile-time known arrays only
** array repetition compile-time known count
ZIG
const a = [_]u8{ 1, 2 };
const b = [_]u8{ 3, 4 };
const joined = a ++ b;        // { 1, 2, 3, 4 }
const zeros = [_]u8{0} ** 4;  // { 0, 0, 0, 0 }

Note that ** is not exponentiation; use std.math.pow(T, base, exp) for that.

Bitwise and shift operators

Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise XOR
~ bitwise NOT
<< shift left
>> shift right (arithmetic for signed types)
<<| saturating shift left

Shift amounts have a type with just enough bits for the width: shifting a u8 needs a u3 amount. A literal or a value the compiler can bound works; a general u32 amount must be cast with @intCast.

ZIG
const std = @import("std");

pub fn main() void {
    const flags: u8 = 0b0000_0101;
    const read: u8 = 0b0000_0001;
    const write: u8 = 0b0000_0010;

    std.debug.print("can read:  {}\n", .{(flags & read) != 0});
    std.debug.print("can write: {}\n", .{(flags & write) != 0});
    std.debug.print("with write: {b:0>8}\n", .{flags | write});
    std.debug.print("toggled:    {b:0>8}\n", .{flags ^ read});
    std.debug.print("shifted:    {d}\n", .{flags << 2});
}
TEXT
can read:  true
can write: false
with write: 00000111
toggled:    00000100
shifted:    20

Bitwise operators have higher precedence than comparison in Zig (unlike C), but parentheses make the intent clear, as above.

Assignment operators

Every binary operator has a compound form: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, +%=, +|= and so on. Plain = is a statement, not an expression: you cannot write a = b = 0 or if (x = 5). That removes the famous = versus == typo from the language. There is no ++ or --; write i += 1.

Precedence

From highest to lowest, roughly:

  1. Postfix: a.b, a[i], f(), a.*, a.?
  2. Prefix: !, -, ~, &, try
  3. * / % ** *% *| ||
  4. + - ++ +% -% +| -|
  5. << >>
  6. & ^ | orelse catch
  7. == != < > <= >=
  8. and
  9. or
  10. Assignment

Zig rejects chained comparisons such as a < b < c. When in doubt, add parentheses. A good habit: never rely on precedence between different families of operators.

Other operators you will meet

  • orelse unwraps an optional with a default (maybe orelse 0); catch handles an error. Both appear in later lessons.
  • a.* dereferences a pointer; &a takes an address.
  • if (cond) x else y is the ternary operator; Zig has no ?:.

Stand-ins you can run

The bit-flag example translates directly to C, where it is the standard way to pack options into one byte.

C Stand-in (C): flags with bitwise operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Short-circuit evaluation is the same idea in every language; here Rust proves the right-hand side is skipped.

Rust Stand-in (Rust): short-circuit and and or

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is the Zig spelling of logical AND?

    Zig uses the words and, or and the symbol !; & is bitwise AND.
  2. 2. Why does if (count) fail when count is a u32?

    Zig has no implicit conversion of integers to bool; write count != 0.
  3. 3. What does [_]u8{0} ** 3 produce?

    ** repeats an array a compile-time-known number of times.
  4. 4. How do you increment a variable i by one?

    Zig has no ++ or -- operators; use compound assignment.
  5. 5. How do you compare two byte-slice strings for equal content?

    == is not defined for slices; std.mem.eql compares the bytes.

Summary

  • bool conditions only; logic uses and, or, ! and short-circuits.
  • Arithmetic, wrapping (+%) and saturating (+|) operators, plus ++ and ** for compile-time arrays.
  • Bitwise operators & | ^ ~ << >> pack and test flags.
  • Assignment is a statement; there is no ++, -- or ?:.
  • Use parentheses whenever you mix operator families.

Next: Arrays and Slices