Operator Precedence

It is very important to understand the precedence of a given operator. Not knowing the order in which an expression will be evaluated can cause obscure bugs. The code looks right and runs just fine, but the end result is wrong. The cause is often an incorrect assumption about the order in which operators are evaluated. Take the following piece of code:

From mathematics you know that the multiplication should be evaluated first then the addition, resulting in 20. If the multiplication didn't have precedence over the addition, the result would be 60. An operator's precedence defines whether it is evaluated before or after another operator, so the precedence defines the order in which the expression is evaluated.

While the precedence of arithmetic operators is well known to most users, this isn't the case for other MEL operators. What is the precedence of the following operators, and subsequently what is the order of their evaluation?

Without knowing the precedence, you'd most likely evaluate them left to right in the order they appear. Using parentheses to group the operators, this would result in:

This may not be what you had intended. In reality the > operator has the greater of the precedences, so it is evaluated first. The — equality operator comes next, followed by the | | or operator, resulting in the following grouping:

The complete lists of operators and their precedence is given in Table 3.5. The operators with the highest precedence are listed first, followed by operators of a lower precedence.

Where operators with the same precedence are encountered in a statement, they are grouped from left to right in the order they appear. For instance both addition and subtraction have the same precedence and so are evaluated left to right in the following code.

There may be times when you need to override the default precedence of an operator. This can be done using the grouping operator ( ). As in mathematics, it has the highest precedence and therefore overrules the precedence of any other operator. For instance, the grouping operator can be used to ensure that the addition happens before the subtraction in the previous code.

When in doubt about an operator's precedence, always use the grouping operator to explicitly define the order in which you want the expressions to evaluate. The grouping operator also helps to state your intentions clearly to other people who may be reading your code.

0 0

Post a comment

  • Receive news updates via email from this site