Nearby lessons
35 of 124C - Operator Associativity
Associativity decides the direction in which operators of equal precedence are evaluated — left to right, or right to left. Learn how it differs from precedence and why a = b = c works.
Precedence vs Associativity
These two rules work together but answer different questions:
| Rule | Question it answers | Example |
|---|---|---|
| Precedence | Which operator binds tighter? | In 2 + 3 * 4, * wins → 14 |
| Associativity | For equal precedence, which side first? | In 100 / 5 * 2, left first → 40 |
Left to Right — The Common Case
/ and * share the same precedence, so C groups them from the left. Getting this backwards changes the answer:
Right to Left — Assignment
Assignment is right-associative, which is exactly why you can chain it. The rightmost = runs first and its result flows leftwards:
The Full Associativity Table
| Precedence | Operators | Associativity |
|---|---|---|
| 1 (highest) | () [] -> . | Left to right |
| 2 | ! ~ ++ -- unary + - * & sizeof (type) | Right to left |
| 3 | * / % | Left to right |
| 4 | + - | Left to right |
| 5 | << >> | Left to right |
| 6 | < <= > >= | Left to right |
| 7 | == != | Left to right |
| 8-10 | & then ^ then | | Left to right |
| 11-12 | && then || | Left to right |
| 13 | ?: | Right to left |
| 14 | = += -= *= /= %= | Right to left |
| 15 (lowest) | , | Left to right |
?:, and assignment. Everything else is left to right. Memorise those three and you know the whole table.Right-to-Left Unary Operators
Because unary operators are right-associative, they stack inwards from the variable outwards:
Nested Conditional Operators
?: is right-associative, so a chain reads naturally as an if/else-if ladder:
What Associativity Does NOT Decide
Associativity controls grouping, not the order in which operands are actually evaluated. Those are different things, and confusing them leads to undefined behaviour:
Common Mistakes
- Assuming
a - b - cmeansa - (b - c)— subtraction is left-associative, so it is(a - b) - c. - Thinking precedence sets evaluation order — in
f() + g(), C may callg()first. - Modifying a variable twice in one expression —
i++ + i++is undefined, not merely confusing. - Relying on the table instead of parentheses —
(a + b) * ccosts nothing and always reads clearly.
- Precedence decides WHICH operator runs first; associativity decides the DIRECTION for ties.
- Most operators are left-to-right.
- Assignment, unary and the conditional operator are right-to-left.
- a = b = c = 5 works because = is right-associative.
- Associativity is not evaluation order of operands — that is separate and often unspecified.