Share

Operator precedence

The order in which various parts of an expression are evaluated affects the result. The operator precedence unambiguously determines the order in which sub-expressions are evaluated.

  • Multiplication and division are performed before addition and subtraction.

    For example, 3 * 4 +2 is the same as 2 + 3 * 4 and gives the answer 14.

  • Exponents and roots are performed before multiplication and addition.

    For example, 3 + 5 ^ 2 is the same as 3 + 5 and gives the answer 28.

    -3 ^ 2 is the same as -3 and gives the answer -9.

  • Use brackets (parentheses) to avoid confusion.

    For example, 2 + 3 * 4 is the same as 2 + (3 * 4) and gives the answer 14.

  • Parentheses change the order of precedence as terms inside in parentheses are performed first.

    For example, (2 + 3) * 4 gives the answer 20.

    or, (3 + 5) ^2 is the same as (3 + 5) and gives the answer 64.

  • You must surround the arguments of a function with parentheses.

    For example, y = sqrt(2), y = tan(x), y = sin(x + z).

  • Relational operators are performed after addition and subtraction.

    For example, a+b >= c+d is the same as (a+b) >= (c+d).

  • Logical operators are performed after relational operators, though parentheses are often added for clarity.

    For example:

    5 == 2+3 OR 10 <= 3*3

    is the same as:

    (5 == (2+3)) OR (10 <= (3*3))

    but is normally written as

    (5 == 2+3) OR (10 <= 3*3).

Precedence

Order Operation Description
1 () function call, operations grouped in parentheses
2 [] operations grouped in square brackets
3 + - ! unary prefix (unary operations have only one operand, such as, !x, -y)
4 cm mm um ft in th unit conversion
5 ^ exponents and roots
6 * / % multiplication, division, modulo
7 + - addition and subtraction
8 < <= > >= (LT, LE, GT, GE) relational comparisons: less than, less than or equal, greater than, greater than or equal
9 == != (EQ, NE) relational comparisons: equals, not equals
10 AND logical operator AND
11 NOT logical operator NOT
12 XOR logical operator XOR
13 OR logical operator OR
14 , separation of elements in a list

Examples of precedence:

Expression Equivalent
a * - 2 a * (- 2)
!x == 0 (!x) == 0
$a = -b + c * d – e $a = ((-b) + (c * d)) – e
$a = b + c % d – e $a = (b + (c % d)) – e
$x = y == z $x = (y == z)
$x = -t + q * r / c $x = ((-t) + ((q * r) / c))
$x = a % b * c + d $x = (((a % b) * c) + d)
$a = b <= c d != e
$a = !b c & d
$a = b mm * c in + d $a = (((b mm) * (c in)) + d)

Was this information helpful?