Operator Precedence & Associativity

 If someone give you a problem, just only with arithmetic operations, you need to be cautious of these two terms: 

  • Operator Precedence
  • Associativity 

For example,

           float x = 7.8 + 5 / 6;                 

The value is not 2.133 which was resulted by firstly adding 7.8 and 5 and dividing the result 12.8 by 6

The value is not 8.63 which was resulted by firstly dividing 5 by 6 and adding the result 0.83 and 7.8  

Points to be noted:

/ and * have the same precedence

+ and - have the same precedence 

When two operator have the same precedence, associativity takes priority.

Explanation

In this example, / had the highest precedence, so first this division operation will be executed. 

printf("5/6 %d\n 5/6 %f \n 5.0/6.0 %d\n 5.0/6.0 %f\n", 5/6, 5/6, 5.0/6.0, 5.0/6.0);

Output

 5/6 0

 5/6 0.833333 

 5.0/6.0 0

 5.0/6.0 0.833333

In our example, 5/6 was taken as integer, so it resulted 0. Finally, this 0 was added to the 7.8, it yielded 7.8

#include <stdio.h>

int main()
{

   float z = 7.8 + 5 / 6;

   printf(" 5/6 %d\n 5/6 %f \n 5.0/6.0 %d\n 5.0/6.0 %f\n", 
          5/6, 5/6, 5.0/6.0, 5.0/6.0);  
   printf("z %f\n", z);

   return 0;
}


Output:

1
2
3
4
5
 5/6 0
 5/6 -0.000000 
 5.0/6.0 1072343722
 5.0/6.0 0.833333
z 7.800000


Have explained here these two terminologies in Python

Comments