Operator Precedence And Associativity In C

Operators in C programming

The blog post “Operator Precedence and Associativity in C” describes the fundamental concepts of operator execution sequence and direction in C programming.

The knowledge of operator precedence and associativity becomes more important when you are using more than one operator for a single expression.  Now you are thinking why I am saying this because if you don’t have an understanding of operator precedence and associativity, then your expression can produce unexpected results.

So let’s first understand what is the meaning of operator precedence…

The operator precedence defines the priority of the operators which means precedence indicates which operator applied first on the given expression. The higher precedence operator is evaluated before the low precedence operator.

But the problem occurs when an expression has two or more than two operators with the same precedence, so to resolve this problem a new term is introduced by the C standard, it is called associativity. The associativity defines the order in which operators of the same precedence are evaluated, which means evaluated from right to left or left to right.

Table of Operator Precedence and Associativity in C

Note: In the below table Precedence of operators decreases from top to bottom.

Operator Precedence And Associativity In C

 

Let see some examples to understand the Operator Precedence And Associativity In C,

Example 1,

What is the output of the below program?

#include<stdio.h>

int main()
{
    int a = 5, b = 10;
    int c;

    c = a * 2 + b;

    printf("\n output = %d", c);

    return 0;
}

Using the precedence table, we can calculate the output of the above-described code. According to the precedence table multiplication operator ( * ) has higher precedence than addition operator ( + ) and assignment operator ( = ) so multiplication will be evaluated first.

c =  a* 2 + b;
c =  5* 2 + 10;
c =  10 + 10;
c =  40;

Example 2,

What is the output of below program?

#include<stdio.h>

int main()
{
    int a = 5, b = 10;
    int c;

    c = a * 2 + b/2;

    printf("\n output = %d", c);

    return 0;
}

In the above example, two operators ( * and / ) has the same precedence, in that situation we need to check the precedence and associativity table. According to table  *  and / has the associativity from the left to right multiplication will be evaluated first.

c = a* 2 + b / 2 ;
c = 5 * 2 + 10 / 2 ;
c = 10 + 10 / 2 ;
c = 10 + 5;
c = 15;

Note: You should always use the parentheses where more than one operator is used with expression. It prevents from the undesired behavior. See the below example,

#include<stdio.h>

int main()
{
    int a = 5, b = 10;
    int c;

    c = ((a*2)+(b/2));

    printf("\n output = %d", c);

    return 0;
}

Recommended Articles for you,