Operator Precedence

From Xojo Documentation


Concept

This section describes the order in which operators are executed in an expression that has two or more operators.

Notes

Operator Precedence determines the order in which operators execute when there is more than one operator in an expression. For example, the expression:

5 + 2 / 3

contains both the division and addition operators. It matters whether the division or the addition takes place first. You can force a particular precedence via parentheses. By default, division has precedence over addition, so this expression would evaluate as 5 plus 2/3. You can force it to do the addition first by writing:

(5 + 2) / 3

It is easy to be confused (especially if you have a mathematical background). The following produces what might be an unexpected result:

-4 ^ 2 = -16

To get the expected result use:

(-4) ^ 2 = 16

The order from highest precedence to lowest is shown in the following table:

Operator Description
. Dot operator
AddressOf Delegate creation operator
IsA, Is Object comparison operators
^ Exponentiation operator
- Negation or the unary minus operator
Not Logical not operator
* / \ Mod Multiplication and division arithmetic operators
- + Subtraction and addition arithmetic operators
= > < >= <= <> Comparison operators
And Bitwise and logical operator
Or Xor Bitwise and logical operator
: Pair creation operator

If there is more than one operator in an expression with the same precedence, they are evaluated in left-to-right order (left associative) in the expression. For example:

Var number As Integer
number = 5 / 100 * 255
// number = 12

All operators are left-associative except for pairs (:) and exponentiation (^).

Left associative means that (foo or bar or baz) will evaluate like ((foo or bar) or baz) instead of (foo or (bar or baz)). Conversely, right associative means that (foo : bar : baz) will evaluate like (foo : (bar : baz)) instead of ((foo : bar) : baz).

Short-Circuit Evaluation

When used within an If..Then statement, once the first expression results to False, none of the subsequent expressions are evaluated. In this example, the IsValid method is not called because the first expression is False. This is referred to as short-circuit evaluation:

Var b As Boolean = False
If b And IsValid("value") Then // IsValid does not get called
...
End If

See Also

-, *, +, /, :, >, >=, <, <=, =, <>, \, ^, AddressOf, And, If, IsA, Mod, Or, Xor operators; If...Then...Else command