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 Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded
Tags: ,

Leave a Reply