Precedence and Associativity of operator in C

/*Precedence and Associativity of operators in C */

operator precedence determines which operation is performed first in an expression with more than one operators with different precedence.

for example :

2+5*3

in  the above example multiplication operator have high precedence as compare to addition operator so,  multiply will happening first as higher precedence than after addition will happening lower precedence.

2+5*3
2+15
17
/*program to demonstrate precedence of an operator*/
#include <stdio.h>
int main()
{
    int a = 2, b = 5, c = 3, d;
    d = a + b * c; // multiplication have higher precedence as compare to addition operator have lower precedence
    printf("d=%d", d);
    return 0;
}

Output:
d=17

Operators Associativity is used when two operator have same precedence appear in an expression. Associativity can either left to right or right to left.

for example: '*' and '/' have same precedence and their associativity is left to right.

18/3*2

18/3 in above example multiplication operator and division operator have same precedence and associativity left to right so, division operation perform first then after multiplication operation.

18/3*2
6*2
12
/*program to demonstrate associtivity of an operator*/
#include <stdio.h>
int main()
{
    int a = 18, b = 3, c = 2, d;
    d = a / b * c;// division and multiplication have same precedence
    printf("d=%d", d);
    return 0;
}

Output:
d=12
Precedence and associativity of operators

precedence

Operator

Description

Associativity

1

()
[]
->
.

Function call
array subscript
arrow operator
Dot operator

Left to Right

2

++  

– – 
+

 – 
!


(data type


sizeof

Increment

Decrement

Unary plus

Unary minus

Logical NOT

One’s complement

Cast operator

Indirection

Address

Size in byte

right-to-left

3

*

/

%

Multiplication

Division

modulus

Left to Right

4

+

-

Addition

Subtraction

Left to Right

5

<< 

>> 

Left shift

Right shift

Left to Right

6

< 

<=

> 

>=

Less than

Less than or equal to

Greater than

Greater than or equal to

Left to Right

7

==

!=

Equal to

Not equal to

Left to Right

8

&

Bitwise AND

Left to Right

9

^

Bitwise XOR

Left to Right

10

|

Bitwise OR

Left to Right

11

&&

Logical AND

Left to Right

12

||

Logical OR

Left to Right

13

? :

Ternary operator

right-to-left

14


+=  -= 
*=  /= 
%=  &= 
^=  != 
<<=  >>=

Assignment operator

right-to-left

15

,

Comma operator

Left to Right

 

solve the problems and write the comment

a = 8, b = 4, c = 2, d = 1, e = 5, f = 20

(i) a + b - (c + d) * 3 % e + f / 9

(ii) a % 6 - b / 2 + (c * d - 5) / e * f

Operator quiz for practice

Comments

Popular posts from this blog

18 Amazing programs in C.