Information Technology Reference
In-Depth Information
Order of Evaluation
An expression can be made up of many nested sub-expressions. The order in which the sub-
expressions are evaluated can make a difference in the final value of the expression.
For example, given the expression 3 * 5 + 2, there are two possible results depending on the
order in which the sub-expressions are evaluated, as shown in Figure 8-3.
￿
If the multiplication is performed first, the result is 17.
￿
If the 5 and the 2 are added together first, the result is 21.
Figure 8-3. Simple order of evaluation
Precedence
You know from your grade school days that in the preceding example, the multiplication must
be performed before the addition because multiplication has a higher precedence than addi-
tion. But unlike grade school days, when you had four operators and two levels of precedence,
things are a bit more complex with C#, which has over 45 operators and 14 levels of
precedence.
The complete list of operators and their precedences is given in Table 8-4. The table lists
the highest precedence operators at the top, and continues down to the lowest precedence
operators at the bottom.
Table 8-4. Operator Precedence: Highest to Lowest
Category
Operators
Primary
a.x f(x) a[x] x++ x-- new typeof checked unchecked
+ - ! ~ ++x --x (T)x
Unary
Multiplicative
* / %
+ -
Additive
Shift
<< >>
< > <= >= is as
Relational and type
Equality
== !=
&
Logical AND
Logical XOR
^
|
Logical OR
Conditional AND
&&
||
Conditional OR
Search WWH ::




Custom Search