Skip to content

SpecificationIV · Expressions and operators

4.7

Precedence and associativity

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

Markdown version

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 levels, from the one that binds tightest (top) to the one that binds loosest (bottom).

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.

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.

ProgramWho goes first

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

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.

  1. 1The expression as written.

  2. 2* has a higher level than +, so 3 * 4 is grouped first.

  3. 3The product is computed: 12.

  4. 4The addition remains: 2 + 12 = 14.

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

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.

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.