Operator precedence & associativity in C

Operator precedence describes the way in which the operations are evaluated. When we have several operations in an expression, each part is evaluated and resolved in a predetermined order decided by the operator precedence.

Operators having higher precedence are solved first as compared to the lower precedence operators.

For example:

5+3*7 // it gives 26

This is so because the multiplication operator (“*”) has higher precedence over the addition operator (“+”), thus the expression 3 * 7 will be solved first and the result of it (i.e., 21) becomes the right operand for the addition, and then the addition is performed as 5 + 21 which returns 26.

Associativity defines how the operators having the same precedence are evaluated.

For example:

10*5/2 // it gives 25

 (“*”) and (“/”) have the same precedence and “left to right” associativity; therefore, 10*5 evaluated first, then its result (50) becomes the second operand for (“/”) and after that 50/2 is evaluated which gives 25.

Operator
Meaning of operator
Associativity
Rank
()
[]
->
.
Functional call (Parentheses)
Array element reference
Indirect member selection
Direct member selection
Left to right
1
!
~
+
-
++
--
&
*
sizeof
(type)
Logical negation
Bitwise(1 's) complement
Unary plus
Unary minus
Increment
Decrement
Address-Of Operator
Pointer reference(indirection)
Returns the size of an object
Type cast(conversion)
Right to left
2
*
/
%
Multiply
Divide
Remainder(modulo-division)
Left to right
3
+
-
Addition
Subtraction
Left to right
4
<<
>>
Left shift
Right shift
Left to right
5
<
<=
>
>=
Less than
Less than or equal
Greater than
Greater than or equal
Left to right
6
==
!=
Equal to
Not equal to
Left to right
7
&
Bitwise AND
Left to right
8
^
Bitwise exclusive OR
Left to right
9
|
Bitwise OR
Left to right
10
&&
Logical AND
Left to right
11
||
Logical OR
Left to right
12
?:
Conditional Operator
Left to right
13
=
*=
/=
%=
+=
-=
&=
^=
|=
<<=
>>=
Assignment Operator
Short-Hand Assignment
Operators
Right to left
14
,
Comma(separator)
Left to right
15

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.