Operator Precedence & Associativity
Precedence Table (Highest to Lowest)
Precedence | Operators | Associativity |
|---|---|---|
1 (highest) |
| Left to right |
2 |
| 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 (lowest) |
| Left to right |
&, ^, and | bind looser than the relational and equality operators, and even looser than the shift operators. This surprises many people and is a frequent source of subtle bugs when mixing bitwise operators with comparisons — always use parentheses in that situation.Use Parentheses for Clarity
Even when you know the precedence table by heart, relying on it in real code makes the code harder for others (and future you) to read quickly. Adding parentheses around the intended grouping costs nothing at runtime and removes all ambiguity.
/* Technically correct, but forces the reader to recall precedence rules */ int result = a + b * c > d && e | f; /* Much clearer with explicit grouping — same behavior, obvious intent */ int resultClear = (a + (b * c) > d) && (e | f);
Worked Example: Mixing &&, ||, Bitwise, and Shift
Consider the following expression, which mixes several operator categories:
int result = 1 << 2 & 6 == 6 || 8 >> 1;
Resolving it step by step using the precedence table above:
==(precedence 7) binds tighter than&and<</>>? No — check the table:<</>>are precedence 5,==is precedence 7, so shifts bind tighter than==. Evaluate shifts first:1 << 2becomes4, and8 >> 1becomes4Expression is now:
4 & 6 == 6 || 4==(7) binds tighter than&(8), so6 == 6evaluates first, giving1Expression is now:
4 & 1 || 4&(8) binds tighter than||(12), so4 & 1evaluates next, giving0Expression is now:
0 || 4, which evaluates to1(true), since4is truthyFinal result:
result = 1
Precedence decides which operator applies first among different operators
Associativity decides the order among operators of equal precedence
Bitwise
&,^,|bind looser than relational and equality operators — a common surpriseWhen mixing operator categories, use parentheses rather than relying on memorized precedence