Arithmetic Operator Precedence

Consider the following expression:

8 + 4 / 2

What is the value of this expression?

If you said 10, you are correct. It is generally accepted that when evaluating arithmetic, division occurs before addition. This is because division has higher Operator Precedence than addition. Precedence is used to remove ambiguity in calculations, and dictates the order in which calculations inside other calculations are executed by computer software.

The list below is a quick reference showing the precedence applied to arithmetic operators within the KnowledgeKube Expression Engine:

Evaluated first:

  • The contents of parentheses
  • Exponents
  • Multiplication, division, integer division and modulus

Evaluated last:

  • Addition and subtraction

Using the above table, we can see that the earlier example of

8 + 4 / 2

is evaluated as

8 + ( 4 / 2 )

Both of these expressions equate to the same value, but one is a little more readable than the other. As discussed in the parentheses section above, we could override the division operator in the above example by writing our own parentheses into the expression, like so:

( 8 + 4 ) / 2

Instead of 10, the new expression evaluates to 6. This is because the addition is now executed before the division, so instead of evaluating 8 + 2, the new expression is equivalent to 12 / 2.

Any time two or more operators in an expression have the same precedence, they are evaluated in the order they appear from left to right.

 

<< Previous: Parentheses ( ( and ) ) | Next: Lesson Summary >>