Operator Associativity

Operator associativity is used when two operators of the same precedence appear in an expression. Associativity can be either from Left to Right or Right to Left. 

Example of Operator Associativity

Let’s evaluate the following expression,

100 / 5 % 2

Both / (division) and % (Modulus) operators have the same precedence, so the order of evaluation will be decided by associativity.

According to the given table, the associativity of the multiplicative operators is from Left to Right. So,

(100 / 5) % 2

After evaluation, the expression will be

20 % 2

Now, the % operator will be evaluated.

0

We can verify the above using the following C program:

// C Program to illustrate operator Associativity
#include <stdio.h>

int main()
{
    // Verifying the result of the same expression
    printf("100 / 5 % 2 = %d", 100 / 5 % 2);

    return 0;
}

Output
100 / 5 % 2 = 0

Operators Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub-expressions.

Operator Precedence and Associativity in C

The concept of operator precedence and associativity in C helps in determining which operators will be given priority when there are multiple operators in the expression. It is very common to have multiple operators in C language and the compiler first evaluates the operater with higher precedence. It helps to maintain the ambiguity of the expression and helps us in avoiding unnecessary use of parenthesis.

In this article, we will discuss operator precedence, operator associativity, and precedence table according to which the priority of the operators in expression is decided in C language.

Similar Reads

Operator Precedence and Associativity Table

The following tables list the C operator precedence from highest to lowest and the associativity for each of the operators:...

Operator Precedence in C

Operator precedence determines which operation is performed first in an expression with more than one operator with different precedence....

Operator Associativity

Operator associativity is used when two operators of the same precedence appear in an expression. Associativity can be either from Left to Right or Right to Left....

Example of Operator Precedence and Associativity

In general, the concept of precedence and associativity is applied together in expressions. So let’s consider an expression where we have operators with various precedence and associativity...

Important Points

There are a few important points and cases that we need to remember for operator associativity and precedence which are as follows:...

Conclusion

It is necessary to know the precedence and associativity for the efficient usage of operators. It allows us to write clean expressions by avoiding the use of unnecessary parenthesis. Also, it is the same for all the C compilers so it also allows us to understand the expressions in the code written by other programmers....