
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Making Error-Free Expressions
|
127
part of the expression is to be evaluated first. This technique works equally well with
Boolean equations.
Discussion
Parentheses are key to writing maintainable and bug-free equations. Not only is your
intention clearly spelled out, but you also override any operator precedence rules
that you might not have taken into account. In fact, the only way to override opera-
tor precedence is to use parentheses (you can use temporary variables to hold partial
results, which aids in readability, but can increase the size of the IL code). Consider
the following equation:
int x = 1 * 2 - -50 / 4 + 220 << 1;
Console.WriteLine("x = " + x);
The value 468 is displayed for this equation.
This is the same equation written with parentheses:
int y = ((1 * 2) - ((-50) / 4) + 220) << 1;
Console.WriteLine("y = " + y);
The same value (468) is also displayed for this equation. Notice how much easier it is
to read and understand how this equation works when parentheses are used. It is
possible to get carried away with the use of parentheses in an equation:
int z = ((((1 * 2) - ((-50) / 4)) + 220) << (1));
Console.WriteLine("z = " + z);
This equation also evaluates to 468, but due to the overuse of parentheses, you can
get lost determining where one set of parentheses begins and