Operators precedence and Associativity

Operators precedence and Associativity 

Operator precedence and associativity means which operators to perform at first. The table below lists the C operators and their precedence and associativity values. The highest precedence level is at the top of the table and as it goes down the associativity goes on decreasing. 

  

OPERATOR PRECEDENCE AND ASSOCIATIVITY 

Symbol           

Name or Meaning 

Associativity 

++ 

Post-increment 

Left to right 

-- 

Post-decrement 

 

( ) 

Function call 

 

[ ] 

Array element 

 

-> 

Pointer to structure member 

 

. 

Structure or union member 

 

++i 

Pre-increment 

Right to left 

--i 

Pre-decrement 

 

! 

Logical NOT 

 

~ 

Bitwise NOT 

 

- 

Unary minus 

 

+ 

Unary plus 

 

& 

Address 

 

* 

Indirection 

 

sizeof 

Size in bytes 

 

new 

Allocate program memory 

 

delete 

Deallocate program memory 

 

(type) 

Type cast [for example, (float) i] 

 

.* 

Pointer to a member (objects) 

Left to right 

->* 

Pointer to a member (pointers) 

 

* 

Multiply 

Left to right 

/ 

Divide 

 

% 

Remainder 

 

+ 

Add 

Left to right 

- 

Subtract 

 

<< 

Left shift 

Left to right 

>> 

Right shift 

 

< 

Less than 

Left to right 

<= 

Less than or equal to 

 

> 

Greater than 

 

>= 

Greater than or equal to 

 

== 

Equal 

Left to right 

!= 

Not equal 

 

& 

Bitwise AND 

Left to right 

^ 

Bitwise exclusive OR 

Left to right 

| 

Bitwise OR 

Left to right 

&& 

Logical AND 

Left to right 

|| 

Logical OR 

Left to right 

: 

Conditional 

Right to left 

= 

Assignment 

Right to left 

*=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= 

Compound assignment 

 

, 

Comma 

Left to right 

           Let's see the above operators in the program below:-  


#include <stdio.h>
void main()
{
    int a = 5;
    int b = 15;
    int c = 25;
    int d;
    d = (b + c) / a// due to associativity first bracket operators will work at first.
    printf(" D is %d "d);
}

    output  

    D is 8 

 

Another example  


#include <stdio.h>
void main()
{
    int a = 5;
    int b = 15;
    int c = 25;
    int d;
    d = b = c = a// value of a will go to c, new value of c go b and new
 value of b go to d.
    /*  
    a = 5,  
    c = a(5) 
    b = c(5) 
    d = b(5) 
    */
    printf(" D is %d "d);
}

    output  

     D is 5 


Follow our page for regular updates.

0 Comments