Operator Precedence
When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. You can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, standard operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence.
The following example illustrates the use of the operator precedence:
Example 1:
Dim Result
Result = 2 + 3 * 4 ' Multiplication is performed first.
'Result has value 14
Result = (2 + 3) * 4 ' Parentheses override precedence.
'Result has value 20
Example 2:
Dim A, B, C
A = 5
B = 10
C = 20
Dim ComparisonResult
ComparisonResult = A + B > C / 2 ' Division is performed first, then addition, then comparison.
'ComparisonResult Outputs: True (10 / 2 = 5, then 5 + 5 = 10, 10 > 10 is False, but corrected if comparison operator order is properly enforced)
ComparisonResult = (A + B) > (C / 2) ' Parentheses enforce precedence.
'ComparisonResult Outputs: True (15 > 10)
Example 3:
Dim X, Y, Z
X = 5
Y = 10
Z = 15
Dim LogicalResult
LogicalResult = X + Y > Z And X < Y ' Addition and comparison are performed first, then logical AND.
'LogicalResult Outputs: False (10 + 5 > 15 is False, and 5 < 10 is True, False And True is False)
LogicalResult = (X + Y > Z) And (X < Y) ' Parentheses enforce precedence.
'LogicalResult Outputs: False (still False And True)
Example 4:
Dim NestedResult
NestedResult = (2 + (3 * 4)) * 5 ' Inner parentheses are evaluated first, then outer.
'NestedResult Outputs: 70 (3 * 4 = 12, 2 + 12 = 14, 14 * 5 = 70)
Example 5:
Dim A, B, C
A = 5
B = 2
C = 10
Dim ClearResult
ClearResult = (A * B) + (C / A) 'Using parentheses to make the expression clear.
'ClearResult Outputs: 12 (5 * 2 = 10, 10 / 5 = 2, 10 + 2 = 12)
See BSL Operators for the complete guide on Arithmetic, Comparison and Logical operators.