运算符优先顺序

表达式中出现多个运算时,将按称为运算符优先顺序的预定顺序对每个部分进行求值和解析。可以使用括号来覆盖该优先顺序,并强制表达式的某些部分先于其他部分进行求值。括号内的运算始终在括号外的运算之前执行。但是,在括号内,保持标准的运算符优先顺序。

表达式包含来自多个类别的运算符时,首先对算术运算符求值,然后对比较运算符求值,最后对逻辑运算符求值。比较运算符都具有相同的优先顺序;也就是说,它们按从左到右的出现顺序进行求值。算术运算符和逻辑运算符按以下优先顺序进行求值。

以下示例说明了运算符优先顺序的用法:

示例 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

示例 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)

示例 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)

示例 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)

示例 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)

有关算术运算符、比较运算符和逻辑运算符的完整指南,请参阅“BSL 运算符”。