Associativity of Operators in C Programming

When some expression in C contains two operators with same/equal priority, the expression gets executed as per the “Associativity of Operators”,

Check below program to understand, why it prints the results as “5” and not “1”

 vim associtivity_in_c.c
#include <stdio.h>
int main(){ /* Associativity of operators :1) Left to Right 2) Right to Left */ /* Multiplication &amp; Division has "Left to Right Associativity" */ /* for Division: / , left side is 3 &amp; right side is 2*5, indicating left side is unambiguous */ /* for Multiplication: * , left side is 3/2 &amp; right side is 5, indicating right side is unambiguous */ /* Since both * and / has same priority and "Left to Right" Associativity, In below example */ /* Division will get executed first since it has "Left" side 3 as unambiguous and then multiplication */ /* Hence result will be 5 */ int a = 3/2*5; printf("a=%d\n", a); /*Above Statement will print result as 5 since 3/2 is equals to 1 due to integer division*/ return 0;
}
 gcc -o associtivity_in_c associtivity_in_c.c
 ./associtivity_in_c

This program will display result as 5.

Leave a Reply

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