演算子の優先度

1つの式で複数の演算が発生すると、各部分が評価され、演算子の優先度と呼ばれる所定の順序で解決されます。カッコを使用して、優先順位をオーバーライドし、式の一部を他の部分より前に評価するように強制できます。カッコ内の演算は、常にカッコ外の演算の前に実行されます。ただし、カッコ内では、標準の演算子の優先度が維持されます。

式に複数のカテゴリの演算子が含まれている場合は、算術演算子が最初に評価され、比較演算子が次に評価され、論理演算子が最後に評価されます。比較演算子はすべて同じ優先度です。つまり、比較演算子は左から右に発生した順に評価されます。算術演算子と論理演算子は、次の優先順位で評価されます。

次の例は、演算子の優先度の使用方法を示しています:

例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演算子を参照してください。