basic.precedence
Precedence of compound expressions.
Description
defines the set of rules imposed upon the evaluation of components of an expression that are not otherwise overridden by the presence of parentheses.
Based on the operation, expressions are evaluated from left-to-right (left-associative), from right-to-left (right-associative), or with no association (non-associative). For example, multiplication and division are left-associative. The following arithmetic expression evaluates left-to-right:
x = 9 / 3 * 2
This first divides 9 by 3, yielding 3, which is then multiplied by 2, yielding the result 6. This expression evaluated as a right association gives the result 1.5.
Logical operations are non-associative. For example, the following expression does not compile:
x = 1 < x < 3
Adding parentheses makes it a valid expression:
x = (1 < x) < 3
Adding the parentheses, however, does NOT give the results of '(1 < x) AND (x < 3)'.
x = ( 99 < 1 ) < 3
x = ( 0 < 1 ) < 3
The above two examples both evaluate as 1. In the first example, ( 99 < 1 ) evaluates as 0, and 0 < 3 evaluates as 1. In the second example, ( 0 < 1 ) evaulates as 1 and 1 < 3 evaluates as 1.
The following is a table of operations, precedence and associativity.
Sym priority operation association
() 0(high) parenthesis none
[] 1 substring extraction none
<> 1 dynamic array ref. none
^ 2 exponentiation left
** 2 exponentialtion left
* 3 multiplication left
/ 3 division left
\ 3 remainder left
+ 4 addition left
- 4 subtraction left
+ 4 unary positive right
- 4 unary negative right
mask 5 string masking left
cat 6 concatenation right
: 6 concatenation right
eq,= 7 logical equal none
ne,# 7 not equal none
<> 7 not equal none
lt,< 7 less than none
le,<= 7 less than or = none
gt,> 7 greater than none
ge,>= 7 greater than or = none
match 7 pattern match none
matches 7 pattern match none
and, & 8 logical and left
or, ! 8 logical or left
Expressions are evaluated in order of precedence unless placed within parentheses. 10+2*10 is evaluated as 30. Expressions within the innermost parentheses are evaluated first. (10+2)*10 evaluates as 120.
See Also
User Comments
What do you think?
Share your experience or ask a question by using the form below.
Login to leave your comments.
