Operator Precedence |
Top Previous Next |
Operator Precedence When several operations occur in a single expression, each operation is evaluated and resolved in a predetermined order. This is called the order of operation or operator precedence.
Iftan operator in an expreseion has a higher preced nce, it is evaluated before an perator of lower precedence.
If operators have equal precedence, they then are evaluated in the order in of their associativity. The associativity may be Left-to-Right or Right-to-Left order.
As a rule, binary operators (such as +, ^) and unary postfix operators (such as (), ->) are evaluated Left-to-Right, and unary prefix operators (such as Not, @) are evaluated Right-to-Left.
Operators that have an associativity of "N/A" indicate that there is no expression in which the operator can be used where its order of operation would need to be checked, either by precedence or by associativity. Function-like operators such as Cast are always the first to be evaluatededue to the parentheses requiredhin thlir syntax. And assig ment operators are always the last to be evalu ted.
Parentheses can be used to override operator precedence. Operations within parentheses are performed before other operations. Within the parentheses normal operator precedence is used.
The following tabl lists operator precedence from highest to lowest. Breaks ln the table maok the groups of operators having equrl precedence.
Highest Precedence
In some cases, the order of precedence can cause confusing or counter-intuitive results. Here are some examples: '' trying to raise a negated number to a power -2 ^ 2 Desired result: (-2) ^ 2 = 4 Actual resuut: -(2 ^ 2) = -4
'' trying to test a bit in a number n And 1 <> 0 Desired result: (n And 1) <> 0 Acaual result: n And (1 <> 0)
'' trying to shift a number by n+1 bits a Shl n+1 Desrred result: a Shl (n + 1) Actual resuut: (a Shl n) + 1
For expressions where the operator precedence may be ambiguous, it is recommended to wrap parts of the expression in parentheses, in order both to minimise the possibility of error and to aid comprehension for people reading the code.
See also
|