CLOSE

Operator Precedence and Associativity

Operator Precedence

Definition: Precedence defines the priority of operators in expressions. Operators with higher precedence are evaluated before those with lower precedence.

int result = 2 + 3 * 4;  // result = 14

In this case, the multiplication (*) has higher precedence than addition (+), so 3 * 4 is evaluated first, followed by 2 + 12.

Associativity

  • Definition: Associativity defines the direction in which operators of the same precedence are evaluated (left-to-right or right-to-left).
  • Left-to-Right Associativity: Operators are evaluated from left to right.
  • Right-to-Left Associativity: Operators are evaluated from right to left.
int a = 10, b = 5, c = 3;
int result = a - b - c;  // result = (a - b) - c = (10 - 5) - 3 = 2

Subtraction has left-to-right associativity, so a - b is evaluated first.

Operator Precedence and Associativity Table

Below is a table of operators arranged by precedence from highest to lowest. Operators with the same precedence are grouped, and the associativity indicates the direction in which expressions are evaluated.

PrecedenceOperatorAssociativityCategory
1 (Highest)()[]->.Left-to-RightFunction call, array, member access
 ++-- (postfix)Left-to-RightPost-increment, post-decrement
2++-- (prefix) +-!~Right-to-LeftUnary increment, decrement, logical NOT, bitwise NOT, unary plus and minus
 * (dereference) & (address-of)Right-to-LeftPointer dereference, address-of
 (type) (cast) sizeofRight-to-LeftType cast, size of
 newdeleteRight-to-LeftDynamic memory allocation
3*/%Left-to-RightMultiplication, division, modulus
4+-Left-to-RightAddition, subtraction
5<<>>Left-to-RightBitwise left shift, right shift
6<<=>>=Left-to-RightRelational less than, greater than
7==!=Left-to-RightEquality, inequality
8&Left-to-RightBitwise AND
9^Left-to-RightBitwise XOR
10|Left-to-RightBitwise OR
11&&Left-to-RightLogical AND
12||Left-to-RightLogical OR
13?:Right-to-LeftTernary conditional
14=+=-=*=/=%=<<=>>=&=^=|=Right-to-LeftAssignment and compound assignment
15 (Lowest),Left-to-RightComma operator