Operator Precedence and Associativity in C
Operator Precedence and Associativity in C
Operator
Precedence Associativity
Description
* Dereference Operator
6 Left-to-Right
Relational greater than, greater than or
> , >=
equal to
12 || Logical OR Left-to-Right
= Assignment
14 Right-to-Left
%= , &= Modulus, bitwise AND assignment
Operator Precedence in C
Operator precedence determines which operation is performed first in an expression with
more than one operator with different precedence.
Example of Operator Precedence
Let’s try to evaluate the following expression,
5+20*15
The expression contains two operators, + (plus), and * (multiply). According to the given
table, the * has higher precedence than + so, the first evaluation will be
5+(20*15)
5+300
Now, the + operator will be evaluated .
305
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 % 4
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)%4
After evaluation, the expression will be
20%4
Important Points
There are a few important points and cases that we need to remember for operator
associativity and precedence which are as follows:
1. Associativity is only used when there are two or more operators of the same
precedence.
2. We can use parenthesis to change the order of evaluation
3. All operators with the same precedence have the same associativity.
4. Precedence and associativity of postfix ++ and prefix ++ are different.
5. Comma has the least precedence among all operators and should be used carefully.
6. There is no chaining of comparison operators in C