Precedence and Associativity

Understanding operator precedence and associativity is crucial in C programming, as it determines the order in which expressions are evaluated. This helps in writing correct and efficient code. Below is a detailed explanation of both concepts.


1. Operator Precedence

Operator precedence defines the order in which different operators in an expression are evaluated. Operators with higher precedence are evaluated before those with lower precedence. Here’s a general hierarchy of operator precedence in C, from highest to lowest:

  • Highest Precedence:
    • Postfix Operators: () (function call), [] (array subscript), -> (structure pointer), . (structure member)
    • Unary Operators: ++ (increment), -- (decrement), + (unary plus), - (unary minus), ! (logical NOT), ~(bitwise NOT), * (dereference), & (address-of), sizeof, type casts (type)
  • Intermediate Precedence:
    • Multiplicative Operators: *, /, %
    • Additive Operators: +, -
    • Bitwise Shift Operators: <<, >>
  • Relational Operators: <, <=, >, >=
  • Equality Operators: ==, !=
  • Bitwise AND: &
  • Bitwise XOR: ^
  • Bitwise OR: |
  • Logical AND: &&
  • Logical OR: ||
  • Conditional Operator: ?:
  • Assignment Operators: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
  • Comma Operator: , (lowest precedence)

2. Operator Associativity

Associativity defines the order in which operators of the same precedence level are evaluated. Operators can be left-to-right or right-to-left in their evaluation.

  • Left-to-Right Associativity:
    • Operators that associate from left to right are evaluated in the order they appear from left to right. Most binary operators, such as arithmetic and bitwise operators, fall into this category.
  • Right-to-Left Associativity:
    • Operators that associate from right to left are evaluated in the reverse order. Assignment operators and the conditional (ternary) operator (?:) are examples of this.

3. Detailed Table of Precedence and Associativity

Here’s a comprehensive table summarizing the precedence and associativity of all operators in C:

Precedence LevelOperatorDescriptionAssociativity
1() [] -> .Function call, array subscript, structure accessLeft-to-right
2++ -- (postfix)Postfix increment and decrementLeft-to-right
3++ -- (prefix), + - ! ~ * &sizeofPrefix increment/decrement, unary operators, type castsRight-to-left
4* / %Multiplication, division, moduloLeft-to-right
5+ -Addition, subtractionLeft-to-right
6<< >>Bitwise left shift, right shiftLeft-to-right
7< <= > >=Relational operatorsLeft-to-right
8== !=Equality operatorsLeft-to-right
9&Bitwise ANDLeft-to-right
10^Bitwise XORLeft-to-right
11``Bitwise OR
12&&Logical ANDLeft-to-right
13|Logical ORLeft-to-right
14?:Ternary conditional operatorRight-to-left
15= += -= *= /= %= >>= <<= &=^= `Assignment operatorsLeft-to-right
16,Comma operatorLeft-to-right
error: Content is protected !!
Open chat
1
Hi,how Can We Help You ?