1.2Operators, precedence and associativity
The idea
Precedence decides which operators grab their operands first; associativity breaks ties. Together they give the fully parenthesised form of an expression.
Think of it like this: In 2 + 3 × 4 the multiplication is "stickier", so it grabs 3 and 4 before the plus gets a turn.
Why it exists
Almost every GATE output puzzle uses an expression whose grouping you must get right before you can evaluate it.
How it works
- Memorise the order: postfix, unary, * / %, + −, shifts, comparisons, == !=, &, ^, |, &&, ||, ?:, assignment, comma.
- Group the tightest operators first and add brackets mentally.
- For operators of equal level, group left to right (assignment and ?: go right to left).
- Only then evaluate the brackets from the inside out.
Worked example: a & b == c
== is tighter than &, so this is a & (b == c), not (a & b) == c. With a = 2, b = 3, c = 4: b == c is 0, so the result is 2 & 0 = 0.
Now play with it
- →Type a & b == c into the lab and read the "grouping" line.
- →Try a << 1 + 2: the plus happens first (shift by 3).
| # | sub-expression evaluated | value |
|---|---|---|
| 1 | (b * c) | 12 |
| 2 | (a + (b * c)) | 14 |
| Looks like | Really means | Why |
|---|---|---|
| x & 1 == 0 | x & (1 == 0) | == binds tighter than & |
| *p++ | *(p++) | postfix ++ binds tighter than * |
| (*p)++ | increment the pointed-to value | parentheses override |
| a + b << 2 | (a + b) << 2 | + binds tighter than << |
| a = b == c | a = (b == c) | assignment is the loosest |
| -a * -b | (−a) * (−b) | unary binds tighter than * |
These re-groupings explain most "surprising" outputs.
| Level (tightest first) | Operators | Associativity |
|---|---|---|
| 1 postfix | a[i] f() x++ x-- | left to right |
| 2 unary | ! ~ + − * & ++x −−x sizeof (cast) | right to left |
| 3 | * / % | left to right |
| 4 | + − | left to right |
| 5 | << >> | left to right |
| 6 | < <= > >= | left to right |
| 7 | == != | left to right |
| 8 | & | left to right |
| 9 | ^ | left to right |
| 10 | | | left to right |
| 11 | && | left to right |
| 12 | || | left to right |
| 13 | ?: | right to left |
| 14 | = += −= … | right to left |
| 15 | , | left to right |
Mnemonic for the traps: the bitwise operators & ^ | sit BELOW the comparisons, so x & 1 == 0 means x & (1 == 0).
Check yourself
With i = 5, what does i + 2 * 3 - 1 evaluate to?
Exam notes (the dense version)
Order of tightness: postfix ( ) [ ] ++ --, then unary ! ~ - * & ++ -- sizeof, then * / %, + -, << >>, < <= > >=, == !=, &, ^, |, &&, ||, ?:, assignment, comma. Most binary operators are left-to-right; assignment, ?: and unary operators are right-to-left. Precedence tells you the grouping, not the order of evaluation.
Previous year questions: Types, Operators & Expressions (2)
PYQs are grouped by topic, so this is the full set for Types, Operators & Expressions; try the ones that match this subtopic. Open all 2 on the topic page.