🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Boolean Logic

Boolean logic combines bool values with and, or, and not to give a new bool.

and needs both sides true

One false side is enough. The whole and result becomes false.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{}\n", .{true and true});
    try out.print("{}\n", .{true and false});
}

or needs only one side true

One true side is enough. The whole or result becomes true.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{}\n", .{false or true});
    try out.print("{}\n", .{false or false});
}

not flips a bool

The ! operator reverses its input. It also reverses a grouped result.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    try out.print("{}\n", .{!false});
    try out.print("{}\n", .{!(2 < 3)});
}

Example

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const age = 20;
    const is_adult = age >= 18;
    const has_ticket = true;
    const can_enter = is_adult and has_ticket;
    const needs_ticket = !has_ticket;
    const can_enter_or_watch = can_enter or needs_ticket;
    try out.print("{}\n", .{can_enter});
    try out.print("{}\n", .{needs_ticket});
    try out.print("{}\n", .{can_enter_or_watch});
}

Key points

  • And: the and keyword gives true only when both sides are true.
  • Or: the or keyword gives true when at least one side is true.
  • Not: the ! operator flips true to false and false to true.
  • Grouping: parentheses group bool parts that must run together.
  • Inputs: and, or, and ! work on bool values, such as the results of comparisons.
  • Result: a logic expression gives a single bool, true or false.

In this example, is_adult is true because 20 is at least 18, and has_ticket is true. The and makes can_enter true. The ! flips has_ticket, so needs_ticket is false, and the final or still prints true because can_enter is true.

Note

Zig spells these operators with the words and and or, not with symbols.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which expression gives true?