Precedence and Associativity of Operators in C

In C programming, expressions can contain multiple operators. Operator precedence determines the order in which operators are evaluated, and associativity determines the order in which operators of the same precedence are evaluated.

What is Operator Precedence?

Operator precedence is a set of rules that defines the sequence in which operators in an expression are applied. Operators with higher precedence are evaluated before operators with lower precedence.

Example: int result = 5 + 3 * 2; // Multiplication (*) has higher precedence than addition (+) // result = 5 + (3 * 2) = 11

What is Operator Associativity?

Associativity defines the direction in which operators of the same precedence are evaluated. It can be either left-to-right or right-to-left.

Example: int x = 10 - 5 - 2; // Subtraction (-) is left-to-right associative // Evaluated as (10 - 5) - 2 = 3

Operator Precedence Table in C (Common Operators)

Here is a detailed list of C operators, their precedence (high to low), and associativity:

  • 1. () [] -> . : Function call, array, member access – (Left to Right)
  • 2. ! ~ ++ -- + - * & sizeof : Unary operators – (Right to Left)
  • 3. * / % : Multiplication, division, modulus – (Left to Right)
  • 4. + - : Addition, subtraction – (Left to Right)
  • 5. << >> : Bitwise shift left/right – (Left to Right)
  • 6. < <= > >= : Relational operators – (Left to Right)
  • 7. == != : Equality and inequality – (Left to Right)
  • 8. & : Bitwise AND – (Left to Right)
  • 9. ^ : Bitwise XOR – (Left to Right)
  • 10. | : Bitwise OR – (Left to Right)
  • 11. && : Logical AND – (Left to Right)
  • 12. || : Logical OR – (Left to Right)
  • 13. ?: : Ternary conditional operator – (Right to Left)
  • 14. = += -= *= /= %= &= |= ^= <<= >>= : Assignment operators – (Right to Left)
  • 15. , : Comma operator – (Left to Right)

Examples of Precedence and Associativity

  • int a = 10, b = 5, c = 2;
  • int result1 = a + b * c; // Multiplication (*) before addition (+), result = 10 + (5*2) = 20
  • int result2 = a - b - c; // Subtraction (-) is left-to-right, result = (10-5)-2 = 3
  • int result3 = a > b && b > c; // Relational operators before logical AND, result = 1 (true)
  • int result4 = a = b = c = 5; // Assignment operators right-to-left, a=b=c=5

Tips to Avoid Precedence Mistakes

  • Use parentheses to make complex expressions clear: (a + b) * c
  • Remember that unary operators have higher precedence than binary operators
  • Be aware of right-to-left associativity in assignments and ternary operators
  • Check operator precedence table when mixing multiple operators to avoid unexpected results

Summary

Understanding operator precedence and associativity is crucial for writing correct expressions. Always use parentheses when in doubt, and remember that different operators have defined precedence levels and associativity directions that affect evaluation order.