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.