Skip to content

Appendix B. Operators and Precedence

This appendix lists the common operators by use. When an expression is not obvious, use parentheses.

This appendix lists the common operators by use. When an expression is not obvious, use parentheses.

B.1 Field, Index, Call

These bind tightly.

x.y
a[i]
f(x)
p.*

Examples:

const x = point.x;
const first = items[0];
const n = len(items);
const value = ptr.*;

B.2 Address and Unary Operators

&x
!ok
-x
~bits

& takes an address.

var x: i32 = 10;
const p = &x;

! negates a boolean.

const bad = !ok;

~ inverts bits.

const y = ~x;

B.3 Multiplication

*  /  %

Example:

const area = width * height;
const q = n / d;
const r = n % d;

B.4 Addition

+  -

Example:

const sum = a + b;
const diff = a - b;

B.5 Bit Shifts

<<  >>

Example:

const high = x << 8;
const low = x >> 8;

B.6 Bitwise Operators

&
^
|

Example:

const masked = x & 0xff;
const toggled = x ^ flag;
const combined = a | b;

B.7 Comparisons

==  !=  <  <=  >  >=

Example:

if (x == y) {
    same();
}

if (n >= 10) {
    large();
}

Comparisons produce bool.

B.8 Boolean Operators

and
or

Example:

if (ready and count > 0) {
    run();
}

if (eof or failed) {
    stop();
}

and and or short-circuit.

B.9 Error and Optional Operators

try expr
expr catch handler
expr orelse fallback

Example:

const n = try readNumber();
const x = parse() catch 0;
const y = maybe orelse 10;

try propagates an error. catch handles an error. orelse handles null.

B.10 Assignment

=  +=  -=  *=  /=  %=  <<=  >>=  &=  ^=  |=

Example:

x = 1;
x += 1;
bits |= flag;

Assignment changes storage. The left side must be assignable.

B.11 Overflow Operators

Zig has wrapping arithmetic operators.

+%  -%  *%
+%= -%= *%=

Example:

x +%= 1;

Use these only when wraparound is the intended operation.

B.12 Saturating Operators

Zig has saturating arithmetic operators.

+|  -|  *|
+|= -|= *|=

Example:

x +|= 1;

If the result would overflow, it clamps to the type limit.

B.13 Exact and Truncating Division

Zig separates some arithmetic operations into builtins.

@divExact(a, b)
@divFloor(a, b)
@divTrunc(a, b)
@mod(a, b)
@rem(a, b)

Use these when the rounding rule matters.

B.14 Parentheses

Parentheses make grouping explicit.

const x = (a + b) * c;

Do not depend on reader memory for precedence in complex expressions.

const ok = (a < b) and (b < c);