Home » Programming Languages » C Programs » Associativity of Operators in C Programming

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(){
        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;

Compile the code as,

 $ gcc -o associtivity_in_c associtivity_in_c.c

Execute the binary as,

 $ ./associtivity_in_c

This program will display result as 5.

Associativity of operators : 1) Left to Right 2) Right to Left . Multiplication & Division has “Left to Right Associativity”

  • For Division: / , left side is 3 & right side is 2*5, indicating left side is unambiguous
  • For Multiplication: * , left side is 3/2 & right side is 5, indicating right side is unambiguous

Since both * and / has same priority and “Left to Right” Associativity, In above example Division will get executed first since it has “Left” side 3 as unambiguous and then multiplication Hence result will be 5.

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment