# Appendix B. Operators and Precedence

### Appendix B. Operators and Precedence

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

### B.1 Field, Index, Call

These bind tightly.

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

Examples:

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

### B.2 Address and Unary Operators

```zig
&x
!ok
-x
~bits
```

`&` takes an address.

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

`!` negates a boolean.

```zig
const bad = !ok;
```

`~` inverts bits.

```zig
const y = ~x;
```

### B.3 Multiplication

```zig
*  /  %
```

Example:

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

### B.4 Addition

```zig
+  -
```

Example:

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

### B.5 Bit Shifts

```zig
<<  >>
```

Example:

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

### B.6 Bitwise Operators

```zig
&
^
|
```

Example:

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

### B.7 Comparisons

```zig
==  !=  <  <=  >  >=
```

Example:

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

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

Comparisons produce `bool`.

### B.8 Boolean Operators

```zig
and
or
```

Example:

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

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

`and` and `or` short-circuit.

### B.9 Error and Optional Operators

```zig
try expr
expr catch handler
expr orelse fallback
```

Example:

```zig
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

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

Example:

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

Assignment changes storage. The left side must be assignable.

### B.11 Overflow Operators

Zig has wrapping arithmetic operators.

```zig
+%  -%  *%
+%= -%= *%=
```

Example:

```zig
x +%= 1;
```

Use these only when wraparound is the intended operation.

### B.12 Saturating Operators

Zig has saturating arithmetic operators.

```zig
+|  -|  *|
+|= -|= *|=
```

Example:

```zig
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.

```zig
@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.

```zig
const x = (a + b) * c;
```

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

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

