In arithmetic and algebra, when a number or expression is both preceded and followed by a binary operation (a calculation involving two operands), a rule is required for which operation should be applied first. From the earliest use of mathematical notation, multiplication took precedence over addition, whichever side of a number it appeared on. Thus 3 + 4 — 5 = 5 — 4 + 3 = 23.
Operator precedence, therefore, determines the order in which operators are evaluated in a statement. Operators with higher precedence are evaluated first.
A simple example can be expressed as follows:
<cfscript> x = 3 + 4 * 5; writeOutput(x); //returns 23 </cfscript>
This is equivalent to wrapping the
4 * 5 in parentheses:
<cfscript> x = 3 + (4 * 5); writeOutput(x); //returns 23 </cfscript>
If we switched the parentheses, the result returned would be entirely different:
<cfscript> x = (3 + 4) * 5; writeOutput(x); //returns 35 </cfscript>
This is an important point to note. Operators have an order of precedence, but this can be overridden using parentheses. Statements within parentheses are always evaluated first, before moving on to the outer statements.
The concept of Associativity determines the order in which operators of the same precedence are processed. For example, consider the following expression (where OP stands for order of precedence):
a OP b OP c
Left-associativity (left-to-right) means that it is processed as:
(a OP b) OP c
Right-associativity (right-to-left) means it is interpreted as:
a OP (b OP c)
The following table details operators order of precedence:
|Precedence||Operator type||Associativity||Individual operators|
Warning: Multiplication and division are of equal precedence, and addition and subtraction are of equal precedence. Using any of the above rules in the order addition first, subtraction afterward would give the wrong answer to
10 - 3 + 2
The correct answer is 9, which is best understood by thinking of the problem as the sum of positive ten, negative three, and positive two.
10 + (-3) + 2
It is usual, wherever you need to calculate operations of equal precedence to work from left to right. The following rules of thumb are useful:
First: perform any calculations inside parentheses (brackets)
Second: Next perform all multiplication and division, working from left to right
Third: Lastly perform all addition and subtraction, working from left to right
17 x 24 / 12
is much easier when worked from right to left, where here the answer is 34.