1.12 Determining Operator Precedence and Associativity

 <  Day Day Up  >  

You want to change the order in which your expression is evaluated by modifying operator precedence.


Technique

Our rule of thumb is to parenthesize the expression being evaluated to prevent any possible operator-precedence defects. Determining whether one operator has precedence over another requires understanding all precedence rules for the language you are using.

Comments

Operator-precedence rules are one of those things you just have to keep in the back of your head no matter how boring it is. As we said earlier, the rule of thumb is to just use parentheses around certain parts of the expression so that we know the order of evaluation. Parentheses are at the top of the food chain, so to speak, for operator precedence.

Operator precedence isn't entirely a programming concept. Back in grade-school arithmetic, you learned that multiplication and division is performed from left to right through the expression, followed by addition and subtraction using the result of the multiplication and division expressions as new operands. For instance, the expression 2 + 4 x 6 equals 26 because you perform the multiplication first, with a result of 24, followed by the addition of 2. If you want to change the order of this evaluation, use parentheses around the parts of the expression you want to perform first. So if we want to perform the addition followed by the multiplication, we use the expression (2 + 4) x 6 to get a result of 36. Table 1.3 shows the available C# operators and the corresponding precedence and associativity. An operator has precedence over another if it appears higher in the table (closer to the top) than the other. For instance, the == operator has a higher precedence than the & operator. If both operators appear on the same level, then you must refer to the associativity of those operators. If the associativity is left, then the expression with the operator that appears leftmost in the table is evaluated first.

Table 1.3. C# Operator Precedence and Associativity

Operators

Associativity

(x) , x , y , f(x) , a[x] , x++ , x-- , new , typeof , sizeof , checked , unchecked

Left

unary + , unary -- , ~ , ++x , --x , (type)x

Left

* , / , %

Left

+ , --

Left

<< , >>

Left

< , > , <= , >= , is , as

Left

== , !=

Left

&

Left

^

Left

Left

&&

Left

Left

?: (ternary)

Right

= , *= , /= , %=.+= , --= , <<= , >>= , &= , = , ^=

Right

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net