Operator precedence is the rule that determines which operator is evaluated first in an expression when multiple operators are present and no parentheses are used while Operator associativity is the rule that determines the direction of evaluation (left-to-right or right-to-left) when operators of the same precedence appear in an expression.
Operator Precedence & Associativity Table (Highest → Lowest)
| Precedence | Operators | Description | Associativity |
|---|---|---|---|
| 1 | () [] -> . | Function call, array, structure | Left → Right |
| 2 | ++ -- | Postfix increment / decrement | Left → Right |
| 3 | ++ -- + - ! ~ * & sizeof | Unary operators | Right → Left |
| 4 | * / % | Multiplicative | Left → Right |
| 5 | + - | Additive | Left → Right |
| 6 | << >> | Bitwise shift | Left → Right |
| 7 | < <= > >= | Relational | Left → Right |
| 8 | == != | Equality | Left → Right |
| 9 | & | Bitwise AND | Left → Right |
| 10 | ^ | Bitwise XOR | Left → Right |
| 11 | | | Bitwise OR | Left → Right |
| 12 | && | Logical AND | Left → Right |
| 13 | || | Logical OR | Left → Right |
| 14 | ?: | Conditional (ternary) | Right → Left |
| 15 | = += -= *= /= %= <<= >>= &= ^= |= | Assignment | Right → Left |
| 16 | , | Comma | Left → Right |
10 + 5 * 2
Answer:20
Explanation:* has higher precedence than +, so multiplication is done first, then addition.
(10 + 5) * 2
Answer:30
Explanation: Parentheses override precedence, so addition happens first, then multiplication.
20 / 5 * 2
Answer:8
Explanation:/ and * have the same precedence, so evaluation is left to right.
a = b = c = 5
Answer:a = 5, b = 5, c = 5
Explanation: Assignment operators associate right to left.
5 > 3 == 1
Answer:1
Explanation:> is evaluated first (5 > 3 → 1), then 1 == 1 evaluates to true (1).
2 << 1 + 1
Answer:8
Explanation:+ has higher precedence than <<, so 1 + 1 = 2, then 2 << 2 = 8.
a & b == c (assume a=1, b=2, c=2)
Answer:1
Explanation:== has higher precedence than &, so b == c → 1, then 1 & 1 = 1? Wait: a & (b == c) → 1 & 1 = 1.Correction: Answer is 1, because equality is evaluated before bitwise AND.
!a == b (assume a=0, b=1)
Answer:1
Explanation:! has higher precedence, so !0 = 1, then 1 == 1 is true.
x = y + z * w (assume y=2, z=3, w=4)
Answer:x = 14
Explanation: Multiplication is done first (3 * 4 = 12), then addition, then assignment.
a ? b : c = d (assume a=0, b=5, c=1, d=9)
Answer:9
Explanation: Assignment has lower precedence than the conditional operator, so (a ? b : c) = d is not valid. Instead, it is parsed as a ? b : (c = d). Since a is false, c gets 9, and the expression evaluates to 9.