Operator Precedence
In C programming, operator precedence determines the order in which operations are performed in an expression. Operators with higher precedence are evaluated before operators with lower precedence.
For example, in the expression "3 + 4 * 5", the multiplication operator (*) has higher precedence than the addition operator (+), so the multiplication is performed first (4 * 5 = 20) and then the addition is performed (3 + 20 = 23).
In cases where operators have the same precedence, the order in which they are evaluated is determined by their associativity. There are two types of associativity: left-to-right and right-to-left.
Operators with left-to-right associativity are evaluated from left to right, while operators with right-to-left associativity are evaluated from right to left. For example, in the expression "3 + 4 - 5", the addition operator (+) and the subtraction operator (-) have the same precedence, but left-to-right associativity, so the addition is performed first (3 + 4 = 7) and then the subtraction is performed (7 - 5 = 2).
The table below shows some common C operators, their precedence and associativity:
Operators | Precedence | Associativity |
---|---|---|
() [] -> . | 1 (highest) | |
! ~ ++ -- + - * & (type) | 2 | right-to-left |
* / % | 3 | left-to-right |
+ - | 4 | left-to-right |
<< >> | 5 | left-to-right |
< <= > >= | 6 | left-to-right |
== != | 7 | left-to-right |
& | 8 | left-to-right |
^ | 9 | left-to-right |
| | 10 | left-to-right |
&& | 11 | left-to-right |
|| | 12 | left-to-right |
?: | 13 | right-to-left |
= += -= *= /= %= &= ^= |= | 14 | right-to-left |
, | 15 | left-to-right |
It's worth noting that there are a few other operators in C that are not listed here, such as the conditional operator (?:) and the size of operator, and also the precedence and associativity of operators may vary depending on the context.