Operators precedence in C

Written by

Pooja Rao

Operator precedence and associativity is a very important aspect of programming as it is essential to know while coding, which operator will be taken first for evaluation as accordingly the results will vary.

As we have BODMAS rule in mathematics, similarly we have operator precedence and associativity in C.

Operator precedence in C

Operator precedence means the order in which an operator in an expression will be evaluated.

For instance: 10*5-2 = ?  Here since multiplication operator has higher precedence hence it will be evaluated first and the answer would be 48 ((10*5)-2 )and not 30 (10*(5-2)).

Operator Associativity in C

Associativity comes into picture when we have operators of the same precedence in an expression.  It lets us know in which direction we need to start our evaluation, from left to right or right to left.

For instance: 10/5*2 = ? Here, division and multiplication have same precedence. However since operands have left to right associativity, that is starting from left we move towards right evaluating. Hence, the answer is 4 ((10*5)/2) and not 1 (10/(5*2)).

Precedence Operator Description Associativity
1 ++ — Suffix/postfix increment and decrement Left-to-right
() Function call
[] Array subscripting
. Structure and union member access
-> Structure and union member access through pointer
(type){list} Compound literal
2 ++ — Prefix increment and decrement Right-to-left
+ – Unary plus and minus
! ~ Logical NOT and bitwise NOT
(type) Type cast
* Indirection (dereference)
& Address-of
sizeof Size-of
_Alignof Alignment requirement
3 * / % Multiplication, division, and remainder Left-to-right
+ – Addition and subtraction
4 << >> Bitwise left shift and right shift
5 < <= For relational operators < and ≤ respectively Left-to-right
> >= For relational operators > and ≥ respectively
== != For relational = and ≠ respectively
6 & Bitwise AND Left-to-right
^ Bitwise XOR (exclusive or)
| Bitwise OR (inclusive or)
7 && Logical AND Left to right
7 || Logical OR
8 ?: Ternary conditional Right-to-Left
9 = Simple assignment Right-to-Left
+= -= Assignment by sum and difference
*= /= %= Assignment by product, quotient, and remainder
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
10 , Comma Left-to-right


Operators precedence in C