What is operator precedence?
- It is the characteristic of the operators that determines the evaluation priority of sub expressions in the absence of brackets.
- Precedence is the priority given to the operator.
Example:
- Operator precedence is why the expression 10 + 4 * 10 is calculated as 10 + 40 which gives 50, not as 14 * 10 which gives 140.
- We say multiplication operator (*) has higher precedence than the addition operator (+), So the multiplication must be performed first.
What is operator associativity?
- Associativity is either left to right or right to left evaluation when operators have the same precedence.
- When we can't decide by operator precedence alone in which order to calculate an expression we must use associativity.
Example:
- Operator associativity is why the expression 8 - 3 - 2 is calculated as 5 - 2 which gives 3, but not as 8 - 1 which gives 7.
- We say that the subtraction (-) is "left associative", so the left subtraction must be performed first.
Operator precedence and associativity:
- The precedence decreases from top to bottom in the given table below.
Operator | Description | Associativity |
---|---|---|
( ) [ ] . -> ++ -- |
Parentheses (function call)
Brackets (array subscript) Member selection via object name Member selection via pointer Postfix increment/decrement |
left-to-right |
++
-- + - ! ~ (type) * & sizeof |
Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (convert value to temporary value of type) Dereference Address (of operand) Determine size in bytes on this implementation |
right-to-left |
* / % | Multiplication/division/modulus | left-to-right |
+ - | Addition/subtraction | left-to-right |
<< >> | Bitwise shift left, Bitwise shift right | left-to-right |
< <= > >= |
Relational less than/less than
or equal to Relational greater than/greater than or equal to |
left-to-right |
== != | Relational is equal to/is not equal to | left-to-right |
& | Bitwise AND | left-to-right |
^ | Bitwise exclusive OR | left-to-right |
| | Bitwise inclusive OR | left-to-right |
&& | Logical AND | left-to-right |
| | | Logical OR | left-to-right |
? : | Ternary conditional | right-to-left |
= += -= *= /= %= &= ^= |= <<= >>= |
Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment |
right-to-left |
, | Separator of expressions | Left to right |
- Parenthesis are also used to group sub-expressions to force a different precedence.
- The parenthesis can be nested, for example the expression (2 * ( 3 + 7 ) ) / 5 is valid and evaluates to 4.
- When the parenthesis are nested, the evaluation starts from innermost parenthesis and continues from innermost to outermost until all expressions are evaluated.
- Parenthesis cant be used to indicate multiplication. For example (10 + 5) (10 + 10) is invalid, while (10 + 5) * (10 + 10) is valid.