Previous: , Up: Expressions   [Contents][Index]

### 6.5 Order of Precedence

When you enter an expression that contains more than one operator, then it may not be clear which operation should be performed first. For example, in the expression `6 + 3 * 4` one might choose to perform the addition first and the multiplication later, yielding ```(6 + 3) * 4 = 9 * 4 = 36```, or one might choose to perform the multiplication first and the addition later, yielding `6 + (3 * 4) = 6 + 12 = 18`. To take care of situations like this, the operators are assigned an order of precedence: an indication of which operator goes first in any situation.

The following list shows groups containing operators of equal precedence, with the groups listed in order of decreasing precedence:

1. `.` `()`
2. `^`
3. Unary minus
4. `*` `/` `%` `mod` `smod` `#`
5. `+` `-`
6. `<` `>`
7. `ge` `le` `gt` `lt` `eq` `ne`
8. `and` `or` `xor` `&` `|`
9. `andif` `orif`

For example, multiplication (`*`) has a higher precedence than addition (`+`), so in our example `6 + 3 * 4`, multiplication goes first and addition second. You can make the addition go first after all by making the order explicit using grouping with parentheses (which has the highest precedence): `(6 + 3) * 4` yields `36`.

All operators except power-taking (`^`) have left associativity: if they are combined with operators of equal precedence, then the operations are evaluated from left to right. For example, in `3 * 4 / 5`, the multiplication and the division have the same order of precedence and are both left associative, so the leftmost operation, in this case the multiplication, goes first, yielding `2` (remember that the example involves integers only). With enforced precedence for the division, through `3 * (4 / 5)`, we get `0`.

The operators with the greatest precedence are grouping with parentheses, and selecting a member from a list or structure (`.`). Unary minus refers to a minus sign applied to a single argument, and it has high precedence. For example, `- 3 + 4` yields `1`, and not `-7`. However, the precedence of power-taking is higher than that of unary minus, so `-3^2` is equal to `-9`. Power-taking has right associativity, so `3 ^ 4 ^ 2` is interpreted as `3 ^ (4 ^ 2) = 3 ^ 16`.

Using parentheses, one can explicitly indicate any desired precedence.

Previous: , Up: Expressions   [Contents][Index]