Notes

Operator Precedence and Associativity in C [ English ]

< PrevNext >

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)

PrecedenceOperatorsDescriptionAssociativity
1() [] -> .Function call, array, structureLeft → Right
2++ --Postfix increment / decrementLeft → Right
3++ -- + - ! ~ * & sizeofUnary operatorsRight → Left
4* / %MultiplicativeLeft → Right
5+ -AdditiveLeft → Right
6<< >>Bitwise shiftLeft → Right
7< <= > >=RelationalLeft → Right
8== !=EqualityLeft → Right
9&Bitwise ANDLeft → Right
10^Bitwise XORLeft → Right
11| Bitwise ORLeft → Right
12&&Logical ANDLeft → Right
13|| Logical ORLeft → Right
14?:Conditional (ternary)Right → Left
15= += -= *= /= %= <<= >>= &= ^= |=AssignmentRight → Left
16,CommaLeft → Right

Examples

Example 1

10 + 5 * 2

Answer:20

Explanation:* has higher precedence than +, so multiplication is done first, then addition.

Example 2

(10 + 5) * 2

Answer:30

Explanation: Parentheses override precedence, so addition happens first, then multiplication.

Example 3

20 / 5 * 2

Answer:8

Explanation:/ and * have the same precedence, so evaluation is left to right.

Example 4

a = b = c = 5

Answer:a = 5, b = 5, c = 5

Explanation: Assignment operators associate right to left.

Example 5

5 > 3 == 1

Answer:1

Explanation:> is evaluated first (5 > 31), then 1 == 1 evaluates to true (1).

Example 6

2 << 1 + 1

Answer:8

Explanation:+ has higher precedence than <<, so 1 + 1 = 2, then 2 << 2 = 8.

Example 7

a & b == c (assume a=1, b=2, c=2)

Answer:1

Explanation:== has higher precedence than &, so b == c1, then 1 & 1 = 1? Wait: a & (b == c)1 & 1 = 1.Correction: Answer is 1, because equality is evaluated before bitwise AND.

Example 8

!a == b (assume a=0, b=1)

Answer:1

Explanation:! has higher precedence, so !0 = 1, then 1 == 1 is true.

Example 9

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.

Example 10

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.

< PrevNext >