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

This program will display result as 5.

Android Android Commands Android Java Applications Application Libraries Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded
Tags: ,

Leave a Reply / Ask Question