C Operator Precedence: Evaluation Order and Associativity Rules
What is C Operator Precedence: Evaluation Order and Associativity Rules? Operator precedence determines which operators are evaluated first in an expression without parentheses (e.g. `*` before `+`). Associativity determines the dire...
How do operator precedence and associativity determine the parsing order of complex compound expressions in C?
Explanation & In-Depth Details
- Level 1: Postfix (`()`, `[]`, `->`, `.`, `x++`)
- Level 2: Unary (`++x`, `--x`, `!`, `~`, `sizeof`, `*ptr`, `&var`, `(cast)`) -> Associativity: Right to Left
- Level 3: Multiplicative (`*`, `/`, `%`)
- Level 4: Additive (`+`, `-`)
- Level 5: Shift (`<<`, `>>`)
- Level 6: Relational (`<`, `<=`, `>`, `>=`)
- Level 7: Equality (`==`, `!=`)
- Level 8: Bitwise (`&`, `^`, `|`)
- Level 9: Logical (`&&`, `||`)
- Level 10: Conditional (`?:`) -> Right to Left
- Level 11: Assignment (`=`, `+=`, etc.) -> Right to Left
- Level 12: Comma (`,`)
Code Example
#include <stdio.h>
int main() {
int a = 10, b = 5, c = 2;
// Without parens: (b * c) evaluated first, then a + 10 -> 20
int result1 = a + b * c;
// With parens: (a + b) evaluated first, then 15 * c -> 30
int result2 = (a + b) * c;
printf("Result 1 (a + b * c): %d\
", result1);
printf("Result 2 ((a + b) * c): %d\
", result2);
return 0;
}Interview Question & Tips
A: When two operators in an expression have the same precedence, associativity determines whether they are grouped from left-to-right (e.g., `a - b - c` -> `(a - b) - c`) or right-to-left (e.g., `a = b = c` -> `a = (b = c)`).
Q: Does operator precedence guarantee function argument evaluation order?
A: No! Precedence determines how operators bind to operands, but the actual runtime evaluation order of function arguments or operands is unspecified by the C standard.
Best Practices
This study reference for C Operator Precedence: Evaluation Order and Associativity Rules is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: