Section 5.8. Operator Precedence


5.8. Operator Precedence

If you include more than one operator in a single line of code, you need to know the order in which VB will evaluate them. Otherwise, the results may be completely different from what you intended. For instance, the following statement:

     x = 5 + 3 * 7 

could be interpreted as:

     x = (5 + 3) * 7 ' --> 56 

or as:

     x = 5 + (3 * 7) ' --> 26 

The rule that defines the order in which a language processes operators is known as the order of precedence . If the order of precedence results in operations being evaluated in an order other than the intended one, you can explicitly override the order of precedence through the use of parentheses. Indeed, complex (or even relatively simple) expressions should include parentheses to avoid any compiler misinterpretation or human confusion. (By the way, the example, once parentheses are removed, evaluates to 26.)

When multiple operators appear at the same level of evaluation (that is, they are not subgrouped with parentheses), they are processed in a specific order of precedence. In some instances, multiple operators appear at the same level of precedence (as are * and /). They are treated as equals as far as precedence is concerned. The following list indicates the order of precedence in evaluation, from first to last.

  1. Exponentiation (^).

  2. Negation (-).

  3. Multiplication and division (*, /).

  4. Integer division (\).

  5. Modulo operator (Mod).

  6. Addition/concatenation and subtraction (+, -).

  7. String concatenation (&).

  8. New in 2003. Arithmetic bit shift (<<, >>).

  9. Comparison and object operators (=, <>, <, <=, >, >=, Like, Is, IsNot, TypeOf); the = operator in this list is the Equal To comparison operator, not the assignment operator. New in 2005. The IsNot operator is new in the 2005 release of VB.

  10. Logical and bitwise negation (Not).

  11. Logical and bitwise conjunction (And, AndAlso). New in 2005. The AndAlso operator is new in the 2005 release of VB.

  12. Logical and bitwise disjunction (Or, OrElse, Xor). New in 2005. The OrElse operator is new in the 2005 release of VB.

Since the AddressOf and GetType operators are implemented like functions, they fall outside of the order of precedence rules for operators.

If multiple operators of the same order of precedence appear at the same level of evaluation, they are processed from left to right.




Visual Basic 2005(c) In a Nutshell
Visual Basic 2005 in a Nutshell (In a Nutshell (OReilly))
ISBN: 059610152X
EAN: 2147483647
Year: 2004
Pages: 712

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