Operator Precedence
Like all languages, C has precedence rules that control the order for evaluating the elements in expressions containing more than one operator. If you're familiar with precedence rules in other languages, you won't find any surprises in C. Table 6.8 shows the “pecking order” established for C's operators.
Three general rules control the order of evaluation:
1.When two operators have unequal precedence, the operator with higher precedence is evaluated first.
2.Operators with equal precedence are evaluated from left to right.
3.You can change the normal order of precedence by enclosing an expression in parentheses. The enclosed expression is then evaluated first. (If paren-theses are nested, inner parentheses have higher precedence than outer ones.)
We'll demonstrate operator precedence with a simple example. Since the multiplication operator (*) has higher precedence than the addition operator (+), the statement
val = 2 + 3 * 4
assigns to val the value of 14 (or 2 + 12) rather than 20 (or 5 * 4). Since parentheses have higher precedence than any operator, they can change the normal precedence order. If you enclose the addition operation in parentheses, as follows
val = (2 + 3) * 4
the addition is done first. Now the statement assigns to val the value 20 (or
5 * 4).
Table 6.8 lists the C operators and their precedence values. The lines in the table separate precedence levels. The highest precedence level is at the top of the table.
Table 6.8 C Operators (from highest to lowest precedence)
Symbol |
Name or Meaning |
Associativity |
( ) |
Function call |
Left to right |
[ ] |
Array element , |
|
. |
Structure or union member |
|
–> |
Pointer to structure member |
|
–– |
Decrement |
Right to left |
++ |
Increment , |
|
:> |
Base operator |
Left to right |
! |
Logical NOT |
Right to left |
~ |
One's complement , |
|
– |
Unary minus , |
|
+ |
Unary plus , |
|
& |
Address , |
|
* |
Indirection , |
|
sizeof |
Size in bytes , |
|
(type) |
Type cast [for example, (float) i] , |
|
* |
Multiply |
Left to right |
/ |
Divide , |
|
% |
Modulus (remainder) , |
|
+ |
Add |
Left to right |
– |
Subtract , |
|
<< |
Left shift |
Left to right |
>> |
Right shift , |
|
< |
Less than |
Left to right |
<= |
Less than or equal , |
|
> |
Greater than , |
|
>= |
Greater than or equal , |
|
== |
Equal |
Left to right |
!= |
Not equal , |
|
& |
Bitwise AND |
Left to right |
^ |
Bitwise exclusive OR |
Left to right |
| |
Bitwise OR |
Left to right |
&& |
Logical AND |
Left to right |
|| |
Logical OR |
Left to right |
? : |
Conditional |
Right to left |
= |
Assignment |
Right to left |
*=, /=, %=, +=, –=, <<=, >>=, &=, ^=, |= |
Compound assignment , |
|