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.
Math operators
Section titled “Math operators”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 = 22a - b = 12a * b = 85-a = -17x / y = 3.4Division / 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.
Changing a variable in place
Section titled “Changing a variable in place”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: 24What 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.)
Comparison operators
Section titled “Comparison operators”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: falseage != 18: trueage > 18: trueage < 18: falseage >= 20: trueage <= 19: falsePython 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.
Logical operators: and, or, !
Section titled “Logical operators: and, or, !”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: falsegets lounge: falseneeds ticket: falseIf 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
Section titled “Bitwise operators”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 = 1000a | b = 1110a ^ b = 0110~a = 11110011a << 1 = 11000a >> 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 theu8.<<and>>shift the bits left or right. Bits pushed off the end are simply dropped.
There are compound versions too: &=, |=, ^=, <<=, >>=.
The shift amount has a special type
Section titled “The shift amount has a special type”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.
Wrapping operators: +%, -%, *%
Section titled “Wrapping operators: +%, -%, *%”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 = 40 -% 1 = 255200 *% 2 = 144250 + 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 *%=.
Saturating operators: +|, -|, *|
Section titled “Saturating operators: +|, -|, *|”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: 255health: 0temp: 127Saturating math is great for volume sliders, health bars and colors: values that should stop at the edge instead of jumping to the other end.
Order of operations
Section titled “Order of operations”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:
1420trueThe 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.
Operators you’ll meet later
Section titled “Operators you’ll meet later”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.
Practice
Section titled “Practice”1. Shopping total
Section titled “1. Shopping total”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: 6103 * 120 is worked out first (360), then added. Storing prices in whole cents like this avoids float rounding.
2. In range?
Section titled “2. In range?”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: trueand joins the two comparisons. level & 1 keeps only the lowest bit, which is 1 for every odd number. level % 2 == 1 works too.
3. Wrap or stop
Section titled “3. Wrap or stop”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: 255240 + 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--; writex += 1. - Comparisons
== != < > <= >=give abool, and can’t be chained. Join them withand. - Logic uses words:
and,or, and!for not. - Bitwise:
& | ^ ~ << >>. A runtime shift amount needs a small type, likeu3for au8. +%wraps around (250 +% 10 is 4 for au8);+|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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Table of Operators: every operator, which types it works on, and an example of each.
- Zig language reference: Precedence: the order Zig applies operators in.
- Zig language reference: Wrapping Operations: when wrapping is guaranteed and how it relates to overflow.
- Zig language reference: @divTrunc: signed division, with
@divFloor,@divCeil,@remand@modnearby.