Precedence and associativity of operators (CNS) (Read 940 times)

Started by Just No Point, October 07, 2015, 04:13:26 am
Share this topic:
Precedence and associativity of operators (CNS)
#1  October 07, 2015, 04:13:26 am
  • ******
If you consider an expression like 3+2*5, the result is different depending if you evaluate the * first (yielding 13) or if you evaluate the + first (yielding 25). To disambiguate expressions such as this, operators are assigned distinct precedence levels. In this case, the precedence of * is higher than the precedence of +, so the * is evaluated first, then the + is applied to the result. So the correct answer is 13.

If two operators share the same precedence, then the expression is evaluated from left to right, except for the unary operators and the assignment operator, which associate right to left. For instance, * and / share the same precedence, so 5.0*5/6 evaluates to 25.0/6, which evaluates to 4.166667. On the other hand, 5/6*5.0 evaluates to 0*5.0, which evaluates to 0.0. In contrast, because unary operators associate right to left, -!0 is grouped as -(!0), which evaluates to -(1), which then evaluates to -1.

If part of an expression is grouped in parentheses (), then that part of the expression is evaluated first. For instance, in the expression (3+2)*5, the + is evaluated first, giving 5*5, which then evaluates to 25. If parentheses are nested, the innermost parentheses are evaluated first.

Operator precedence is basically the same as in C. The complete list of operator precedence, from highest to lowest, is as follows:

Operator(s)          lPrecedence Level
! ~ - (unary operators)lHighest
** l
* / %    l
+ -    l
> >= < <=    l
= != intervals    l
:=   l
&    l
^    l
|    l
&&    l
^^    l
||    lLowest

Programmers are encouraged to parenthesize as necessary to maintain clarity. Otherwise, bugs due to subtle misunderstanding of operator precedence are almost assured.