Operators Precedence and Associativity
Operators Precedence and Associativity
Precedence Rule
Precedence is used to determine the order in which operators with different precedence in a complex expression are evaluated.
Associativity Rule:
Associativity is used to determine the order in which operators with the same precedence are evaluated in a complex expression.
Precedence is applied before associativity to determine the order in which expressions are evaluated. Associativity is then applied, if necessary.
When several operations are combined into one C expression the compiler has to rely on a strict set of precedence rules to decide which operation will take preference.
Operator | Associativity |
( ) [ ] -> .(dot) | left to right |
++ --(postincrement/decrement) ++ --(preincrement/decrement) | left to right |
! ~ +(unary) -(unary) * & sizeof | right to left |
(type) | right to left |
* / % | left to right |
+ - | left to right |
<< , >> | left to right |
<, <=, >, >= | left to right |
== != | left to right |
& | left to right |
^ | left to right |
| | left to right |
&& | left to right |
|| | left to right |
? : | right to left |
= += -= *= /= %= &= ^= |= <<= >>= | right to left |
<<= >>= | right to left |
, | left to right |
Examples:
The following is a simple example of precedence:
2 + 3 * 4
This expression is actually two binary expressions, with one addition and one multiplication operator. Addition has a precedence of 12, multiplication has a precedence of 13 from above table. This results in the multiplication being done first, followed by the addition. The result of the complete expression is 14.
The following is a simple example of Associativity:
2 * 3 / 4
This expression is actually two binary expressions, with one multiplication and one division operator. But both multiplication and division has a precedence of 13(same precedence). Hence, apply the associativity rule as given in table above i.e left to right. This results in the multiplication being done first, followed by the division. The result of the complete expression is 1.