# 4.7 Precedence and associativity

> When an expression has several operators, precedence decides which applies first: `2 + 3 * 4` is 14, not 20.

Web page: https://pseudolearn.app/en/spec/expresiones/precedencia

> **In one sentence**
>
> When an expression has several operators, precedence decides which applies first: `2 + 3 * 4` is 14, not 20.

## 4.7.1 How it works

Every operator has a **level**. Higher levels grab their operands first. From strongest to weakest:

**Figure 4.7-1: The precedence ladder**

Nine steps from top to bottom: postfix; sign and Not; power; product, division, div and mod; sum, subtraction and concatenation; order; equality; And; Or. Unary operators and power associate to the right.

The precedence levels, from the one that binds tightest (top) to the one that binds loosest (bottom).

When two operators of the same level follow each other, **associativity** decides. Almost all associate to the left: `10 - 4 - 3` is `(10 - 4) - 3`, which is 3. Unary operators and power associate to the right.

### Program: Who goes first

```pseudolearn
Algorithm Precedencia
  Write 2 + 3 * 4, " ", (2 + 3) * 4, " ", 10 - 4 - 3, " ", 2 ^ 3 ^ 2;
  Write 1 + 2 < 4 And Not False, " ", 2 * 3 = 6 Or False;
EndAlgorithm
```

**Output**

```text
14 20 3 512
true true
```

*The program finishes normally.*

In the second line, the arithmetic is computed first, then the comparisons and finally `And` and `Or`. That is why conditions read naturally without parentheses.

**Figure 4.7-2: The tree of 2 + 3 * 4**

The expression 2 + 3 * 4 is grouped as a tree with + at the root, 2 on the left and 3 * 4 on the right. The product reduces to 12 and the sum to 14.

How `2 + 3 * 4` is grouped. The product sits lower in the tree because it is computed first.

1. Step 1: The expression as written.
2. Step 2: `*` has a higher level than `+`, so `3 * 4` is grouped first.
3. Step 3: The product is computed: 12.
4. Step 4: The addition remains: 2 + 12 = 14.

> **Note**
>
> Parentheses always win. If in doubt, add them: `(a + b) / 2` makes your intent clear and costs nothing.

> **Limit**
>
> Two places where precedence surprises:
>
> - The sign binds tighter than power: `-2 ^ 2` is 4.
> - `Not` binds tighter than comparisons: write `Not (a = b)` or, better, `a <> b`.

**In short**
- First postfix, then unary, power, product, sum, order, equality, `And` and `Or`.
- At the same level grouping is to the left, except unary and power.
- Parentheses change the order.

**See also**
- [4.1 Arithmetic operators](https://pseudolearn.app/en/spec/expresiones/aritmeticos.md)
- [4.3 Power](https://pseudolearn.app/en/spec/expresiones/potencia.md)
- [4.5 Logical operators](https://pseudolearn.app/en/spec/expresiones/logicos.md)
