Join Regular Classroom : Visit ClassroomTech

Operator Precedence and Associativity in C

Type Of Operator

Operators

Associativity

 
()  []              .
Left to Right
Unary
!  ~  ++  —  *  &  (type)  sizeof()
+   –               
 Right to left
Arithmetic
*  /  %
Left to Right
Arithmetic
+   –
Left to Right
Shift
<<   >>
Left to Right
Comparison
<  <=  >  >=
Left to Right
Comparison
==  !=
Left to Right
Bitwise
&
Left to Right
Bitwise
^
Left to Right
Bitwise
|
Left to Right
Logical
&&
Left to Right
Logical
||
Left to Right
Ternary
?:
Right to left
Assignment
= +=  -=  *=  /=  %=  &=  ^=  |=
<<=  >>=
Right to Left
 
Comma
,
Left to Right
Don’t know what is Operator in C? Read: Operators in C

Precedence: It is basically the priority of the operators which will be executed first. The Operators which are in the upper rows of the table will be executed first and gradually as we go downward the operators will be lesser priority and will be executed after executing all the operators having higher priority than that.

Associativity: If more than one same priority operators exist side by side then from which end c program will be executed is decided by associativity.

Some times from left side the operators starts executing and sometime from right side the operators starts executing depending on the associativity of that type of operators.

Example 1: *p++

In this example there 2 operators are used * and ++ both are unary operators so they have same priority now we have to check the associativity. The associativity of unary operator is right to left so right  operator will execute first and then left one so ++ will be executed first then *. So the equivalent expression will be (*(p++))

If the expression be ++*p then equivalent expression will be (++(*p)).

Example 2:  a = 15 – 2*6

In this example 3 operators are used = , – and * among them according to the precedence table * has higher priority then – and then = so 2*6 will be executed first and the expression will be  a = 15 – 12 . Then – will be executed and  a = 3 . Now = will be in action as = is a assignment operator it puts whatever value it gets on his right side to the left side variable so it will assign 3 inside variable a .

You Missed
Also Checkout