Operator Precedence & Associativity in C
When an expression contains multiple operators, **operator precedence** decides
which operator is evaluated first, and **associativity** decides
which direction the expression is evaluated from.
What is Operator Precedence?
Operator Precedence means the priority level of operators. Operators with higher precedence execute before those with lower precedence.
Example:
Expression →
10 + 20 * 3
Multiplication (*) has higher precedence → so 20 * 3 happens first.
What is Associativity?
Associativity tells whether an expression is evaluated **left-to-right** or **right-to-left** when multiple operators have the same precedence.
Example:
a - b - c
Subtraction is left-to-right associative → evaluated as (a - b) - c
Operator Precedence Table
Highest → Lowest Precedence 1. ++ -- (unary), !, ~, sizeof 2. * / % 3. + - 4. << >> 5. < <= > >= 6. == != 7. & 8. ^ 9. | 10. && 11. || 12. ?: (ternary) 13. =, +=, -=, *=, etc. 14. ,
(This is simplified for beginner clarity.)
Associativity Rules
Left-to-Right Associativity: + - * / % < > <= >= == != && || Right-to-Left Associativity: = += -= *= /= ! ~ ++ -- sizeof ?: (ternary)
Example 1 – Precedence of *, +
#include <stdio.h>
int main() {
int result = 10 + 20 * 3;
// 20 * 3 = 60
// 10 + 60 = 70
printf("Result = %d", result);
return 0;
}
Example 2 – Parentheses Change Precedence
#include <stdio.h>
int main() {
int a = (10 + 20) * 3;
// 10 + 20 = 30
// 30 * 3 = 90
printf("a = %d", a);
return 0;
}
Example 3 – Pre/Post Increment & Multiplication
#include <stdio.h>
int main() {
int a = 5;
int result = ++a * 3;
// ++a happens first → a = 6
// 6 * 3 = 18
printf("Result = %d", result);
return 0;
}
Example 4 – Left-to-Right Associativity
#include <stdio.h>
int main() {
int x = 20 - 5 - 3;
// (20 - 5) = 15
// (15 - 3) = 12
printf("x = %d", x);
return 0;
}
Example 5 – Right-to-Left Associativity
#include <stdio.h>
int main() {
int a;
a = 5 + 3 * 2;
printf("a = %d\n", a);
int b;
b = a = 20;
printf("b = %d", b);
return 0;
}
Example 6 – Complex Expression Evaluation
#include <stdio.h>
int main() {
int a = 5, b = 10, c = 2;
int result = a + b * c - ++a;
// Step 1: ++a → a becomes 6
// Step 2: b * c = 20
// Step 3: a + (b*c) - new a → 5 + 20 - 6 = 19
printf("Result = %d", result);
return 0;
}
Diagram – How Precedence Works
Expression: 5 + 3 * 2
* (multiplication)
|
v
5 + (3 * 2)
|
v
5 + 6
|
v
11
Practice Questions
- Define operator precedence and associativity.
- Why are parentheses important in expressions?
- Evaluate: 12 + 6 / 3 * 2
- Evaluate: 10 - 5 - 2 (explain associativity)
- Write a program that shows precedence of ++ and *
Practice Task
Write a program to evaluate and print the result of the expression:
(a + b) * c - (b / a) + ++c
Choose appropriate values for a, b, and c.