Skip to content

Zig Operators

Operators are the symbols that do work on values: + adds, < compares, and combines two conditions. Most of Zig’s operators look just like C’s, so you’ll feel at home fast. There are a few differences worth knowing, though: there’s no ++, the logical operators are words, and Zig has two extra families of math operators for when a number runs out of room. One more thing that makes Zig easy to read: there’s no operator overloading, so + always means plain addition and never secretly calls a function.

The basic math operators work on integers and floats:

const std = @import("std");
pub fn main() void {
const a: i32 = 17;
const b: i32 = 5;
std.debug.print("a + b = {d}\n", .{a + b});
std.debug.print("a - b = {d}\n", .{a - b});
std.debug.print("a * b = {d}\n", .{a * b});
std.debug.print("-a = {d}\n", .{-a});
const x: f64 = 17.0;
const y: f64 = 5.0;
std.debug.print("x / y = {d}\n", .{x / y});
}

Output:

a + b = 22
a - b = 12
a * b = 85
-a = -17
x / y = 3.4

Division / and remainder % work too, with one rule from Zig Integers: on integers they drop the remainder (17 / 5 is 3), and for signed integers known only at runtime you have to pick how to round with @divTrunc, @divFloor or @divCeil (and @rem or @mod for the remainder). On unsigned integers and floats, plain / and % are fine.

Each math operator has a shortcut that updates a variable: +=, -=, *=, /=, %=. score += 5 means score = score + 5.

const std = @import("std");
pub fn main() void {
var score: i32 = 10;
score += 5;
score -= 3;
score *= 2;
std.debug.print("score: {d}\n", .{score});
}

Output:

score: 24

What Zig doesn’t have is ++ and --. If you’re coming from C, Java or JavaScript, your fingers will type i++ anyway:

const std = @import("std");
pub fn main() void {
var count: u32 = 0;
count++;
std.debug.print("{d}\n", .{count});
}
main.zig:5:12: error: expected expression, found ';'
count++;
^

Write count += 1; instead. (In Zig, ++ is a different operator: it joins two arrays, as in "ab" ++ "cd". You’ll see it in Zig Strings and Zig Arrays.)

Comparisons give you a bool, true or false:

const std = @import("std");
pub fn main() void {
const age: u32 = 20;
std.debug.print("age == 18: {}\n", .{age == 18});
std.debug.print("age != 18: {}\n", .{age != 18});
std.debug.print("age > 18: {}\n", .{age > 18});
std.debug.print("age < 18: {}\n", .{age < 18});
std.debug.print("age >= 20: {}\n", .{age >= 20});
std.debug.print("age <= 19: {}\n", .{age <= 19});
}

Output:

age == 18: false
age != 18: true
age > 18: true
age < 18: false
age >= 20: true
age <= 19: false

Python lets you write 0 < x < 10. Zig doesn’t, because in most languages that silently means something else ((0 < x) < 10, comparing a bool with a number):

const std = @import("std");
pub fn main() void {
const x: u32 = 5;
std.debug.print("{}\n", .{0 < x < 10});
}
main.zig:5:37: error: comparison operators cannot be chained
std.debug.print("{}\n", .{0 < x < 10});
^

Join two comparisons with and instead: 0 < x and x < 10.

To combine conditions, Zig uses the words and and or, plus ! for “not”:

const std = @import("std");
pub fn main() void {
const has_ticket = true;
const is_vip = false;
const age: u32 = 16;
std.debug.print("can enter: {}\n", .{has_ticket and age >= 18});
std.debug.print("gets lounge: {}\n", .{is_vip or age < 12});
std.debug.print("needs ticket: {}\n", .{!has_ticket});
}

Output:

can enter: false
gets lounge: false
needs ticket: false

If you type C’s && or || by habit, the compiler tells you to use and and or. Zig Booleans covers these in more depth.

Bitwise operators work on the individual bits of an integer. You’ll use them for flags, file formats, hashing and hardware. Printing with {b} shows the bits, and {b:0>4} pads to 4 digits with zeros:

const std = @import("std");
pub fn main() void {
const a: u8 = 0b1100;
const b: u8 = 0b1010;
std.debug.print("a & b = {b:0>4}\n", .{a & b});
std.debug.print("a | b = {b:0>4}\n", .{a | b});
std.debug.print("a ^ b = {b:0>4}\n", .{a ^ b});
std.debug.print("~a = {b:0>8}\n", .{~a});
std.debug.print("a << 1 = {b:0>5}\n", .{a << 1});
std.debug.print("a >> 2 = {b:0>4}\n", .{a >> 2});
}

Output:

a & b = 1000
a | b = 1110
a ^ b = 0110
~a = 11110011
a << 1 = 11000
a >> 2 = 0011
  • & (AND): a bit is 1 if it’s 1 in both.
  • | (OR): 1 if it’s 1 in either.
  • ^ (XOR): 1 if it’s 1 in exactly one.
  • ~ (NOT): flips every bit. Notice it flips all 8 bits of the u8.
  • << and >> shift the bits left or right. Bits pushed off the end are simply dropped.

There are compound versions too: &=, |=, ^=, <<=, >>=.

Here’s a Zig rule that surprises people. When you shift a u8, the shift amount must fit in a u3, because shifting an 8-bit number by 8 or more makes no sense. With a fixed number like << 3 the compiler checks it for you, but a variable needs the right type:

const std = @import("std");
pub fn main() void {
var flags: u8 = 0;
var bit: u8 = 3;
bit += 0;
flags |= @as(u8, 1) << bit;
std.debug.print("{d}\n", .{flags});
}
main.zig:7:28: error: expected type 'u3', found 'u8'
flags |= @as(u8, 1) << bit;
^~~

Declare bit as a u3 (for a u32 it would be u5, for a u64 a u6):

const std = @import("std");
pub fn main() void {
var flags: u8 = 0;
var bit: u3 = 3;
flags |= @as(u8, 1) << bit; // turn on bit 3
bit = 0;
flags |= @as(u8, 1) << bit; // turn on bit 0
std.debug.print("flags: {b:0>8} ({d})\n", .{ flags, flags });
}

Output:

flags: 00001001 (9)

@as(u8, 1) gives the 1 a real type. A bare 1 is a comptime_int, and the compiler can’t shift a number with no size by an amount it only learns at runtime.

A u8 holds 0 to 255. What’s 250 + 10? With the normal +, Zig treats going past the limit as a bug: it’s a compile error when the compiler can see it, and a crash with a clear message in debug builds. That’s covered in Zig Integer Overflow.

Sometimes, though, you want the number to wrap around like a car’s odometer: after 255 comes 0. Add % to the operator:

const std = @import("std");
pub fn main() void {
const a: u8 = 250;
std.debug.print("250 +% 10 = {d}\n", .{a +% 10});
std.debug.print("0 -% 1 = {d}\n", .{@as(u8, 0) -% 1});
std.debug.print("200 *% 2 = {d}\n", .{@as(u8, 200) *% 2});
}

Output:

250 +% 10 = 4
0 -% 1 = 255
200 *% 2 = 144

250 + 10 is 260, which is 4 more than 256, so it wraps to 4. Wrapping is what you want for hash functions, checksums, random number generators and counters that are meant to roll over. The compound forms are +%=, -%= and *%=.

The other option is to stop at the limit. Add | to the operator and the result sticks at the largest or smallest value the type can hold:

const std = @import("std");
pub fn main() void {
var volume: u8 = 250;
volume +|= 10;
std.debug.print("volume: {d}\n", .{volume});
var health: u8 = 3;
health -|= 5;
std.debug.print("health: {d}\n", .{health});
const temp: i8 = 120;
std.debug.print("temp: {d}\n", .{temp +| 100});
}

Output:

volume: 255
health: 0
temp: 127

Saturating math is great for volume sliders, health bars and colors: values that should stop at the edge instead of jumping to the other end.

When you mix operators, Zig follows the usual math rules: *, / and % before + and -, and comparisons after math. Parentheses always win:

const std = @import("std");
pub fn main() void {
std.debug.print("{d}\n", .{2 + 3 * 4});
std.debug.print("{d}\n", .{(2 + 3) * 4});
const n: u32 = 6;
std.debug.print("{}\n", .{n & 1 == 0});
}

Output:

14
20
true

The last line is a nice difference from C. In Zig, the bitwise operators &, | and ^ bind tighter than ==, so n & 1 == 0 means (n & 1) == 0, “is n even?”. In C the same code means n & (1 == 0), a classic bug. The full list is in the precedence table, but when in doubt, add parentheses. They cost nothing and help the next reader.

A few more operators belong to features you haven’t seen yet:

Operator What it does Lesson
a ++ b Join arrays (compile time only) Zig Arrays
&x, p.* Take an address, follow a pointer Zig Pointers
a orelse b, x.? Default for null, unwrap an optional Zig Optionals
a catch b, try a Handle an error Zig Try & Catch

Older code also uses a ** 3 to repeat an array. That operator was removed in Zig 0.17: to fill an array with one value, write const zeros: [5]u8 = @splat(0); instead.

And there’s no ? : ternary operator. Zig’s if can return a value instead, as you’ll see in Zig If…Else.

Start with var total: u32 = 0;, add a price of 450, add 3 items of 120, then take off a 200 discount, all with compound assignment. Print total: 610.

Hint: +=, * inside the +=, and -=.

Show solution
const std = @import("std");
pub fn main() void {
var total: u32 = 0;
total += 450;
total += 3 * 120;
total -= 200;
std.debug.print("total: {d}\n", .{total});
}

Output:

total: 610

3 * 120 is worked out first (360), then added. Storing prices in whole cents like this avoids float rounding.

Given const level: u32 = 7;, print whether it’s between 1 and 10 (inclusive) and whether it’s odd. Expected output: in range: true, odd: true.

Hint: you can’t chain 1 <= level <= 10. For odd, check the lowest bit with & 1.

Show solution
const std = @import("std");
pub fn main() void {
const level: u32 = 7;
const in_range = 1 <= level and level <= 10;
const odd = level & 1 == 1;
std.debug.print("in range: {}, odd: {}\n", .{ in_range, odd });
}

Output:

in range: true, odd: true

and joins the two comparisons. level & 1 keeps only the lowest bit, which is 1 for every odd number. level % 2 == 1 works too.

A u8 brightness starts at 240. Add 30 to one copy with wrapping and to another with saturation, and print both: wrap: 14, stop: 255.

Hint: +%= and +|=.

Show solution
const std = @import("std");
pub fn main() void {
var wrap: u8 = 240;
var stop: u8 = 240;
wrap +%= 30;
stop +|= 30;
std.debug.print("wrap: {d}, stop: {d}\n", .{ wrap, stop });
}

Output:

wrap: 14, stop: 255

240 + 30 is 270. Wrapping takes away 256 and leaves 14. Saturating stops at the u8 maximum, 255.

  • Math: + - * / % and their compound forms like +=. There’s no ++ or --; write x += 1.
  • Comparisons == != < > <= >= give a bool, and can’t be chained. Join them with and.
  • Logic uses words: and, or, and ! for not.
  • Bitwise: & | ^ ~ << >>. A runtime shift amount needs a small type, like u3 for a u8.
  • +% wraps around (250 +% 10 is 4 for a u8); +| stops at the limit (255).
  • Plain + treats overflow as a bug. Bitwise & binds tighter than ==, unlike C. No operator overloading.

Next up: Zig Booleans, true, false and how to combine conditions.

Quick check

1. How do you add 1 to var count: u32 in Zig?
2. For const a: u8 = 250;, what is a +| 10?
3. What does 0 < x < 10 do in Zig?
4. In Zig, how is n & 1 == 0 grouped?