OPERATOR PRECEDENCE

When Visual Basic evaluates a complex expression, it must decide the order in which to evaluate operators. For example, consider the expression 1 + 2 * 3 / 4 + 2. The following text shows three orders in which you might evaluate this expression to get three different results:

1 + (2 * 3) / (4 + 2) = 1 + 6 / 6 = 2
1 + (2 * 3 / 4) + 2 = 1 + 1.5 + 2 = 4.5
(1 + 2) * 3 / (4 + 2) = 3 * 3 / 6 = 1.5
 

Precedence determines which operator Visual Basic executes first. For example, the Visual Basic precedence rules say the program should evaluate multiplication and division before addition, so the second equation is correct.

The following table lists the operators in order of precedence. When evaluating an expression, the program evaluates an operator before it evaluates those lower than it in the list.

OPERATOR DESCRIPTION
( ) Grouping (parentheses)
^ Exponentiation
- Negation
*, / Multiplication and division
Integer division
Mod Modulus
+, -, + Addition, subtraction, and concatenation
& Concatenation
<<, >> Bit shift
=, <>, <, <=, >, >=, Like, Is, IsNot, TypeOf ... Is All comparisons
Not Logical and bitwise negation
And, AndAlso Logical and bitwise And with and without short-circuit evaluation
Xor, Or, OrElse Logical and bitwise Xor, and Or with and without short-circuit evaluation

When operators are on the same line in the table, or if an expression contains more than one instance of the same operator, the program evaluates them in left-to-right order. For example, * and / are on the same line in the table so in the expression 12 * 4 / 20 Visual Basic would perform the multiplication first. (Of course, it wouldn’t matter much in this example because the result should be the same either way, at least within the limits of the computer’s precision.)

Parentheses are not really operators, but they do have a higher precedence than the true operators, so they’re listed to make the table complete. You can always use parentheses to explicitly dictate the order in which Visual Basic will perform an evaluation.

If there’s the slightest doubt about how Visual Basic will handle an expression, add parentheses to make it obvious. Even if you can easily figure out what an expression means, parentheses often make the code even easier to read and understand. There’s no extra charge for using parentheses, and they may avoid some unnecessary confusion.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.150.75