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. When operators are on the same line, or if an expression contains more than one instance of the same operator, the program evaluates them in left-to-right order.

Open table as spreadsheet

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

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. There’s no extra charge for using parentheses, and they may avoid some unnecessary confusion.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

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