Operators are used to perform operations on expressions. There are two kinds of operators: unary and binary operators. Unary operators take one operand (expression), binary operators take two operands. Example:
3-8 ; - is a binary operator -(3*2) ; * is binary, - is unary here
Since the unary operator - (negation) has a higher precedence than the binary operator * (multiplication), parentheses are necessary to perform the multiplication first. To be able to know when parentheses are required, you need to know the precedence of all operators.
This table lists all operators and their precedence level:
Operator | Association | Precedence level |
new | none | 9 |
. (member) | left | 8 |
! (boolean negation) - (arithmetic negation) |
none | 7 |
^ (power) | left | 6 |
* (multiplication) / (division) % (modulus) |
left | 5 |
+ (addition) - (subtraction) |
left | 4 |
== (equality) != (inequality) < (less than) > (more than) <= (less than or equal to) >= (more than or equal to) |
left | 3 |
&& (boolean AND) | | (boolean OR) |
left | 2 |
= (assignment) | right | 1 |
One operator is not listed here: the |...| (modulus squared) operator, because it is parenthetic and therefore does not have a precedence level (like functions, it always has the highest precedence).
Note that the - (negation) operator has higher precedence than the ^ (power) operator, which might not be what you would expect:
-x^2 -> -(x^2) ; might be unexpected (-x)^2 ; use this instead
The term association may need some further explanation. An operator which associates to the left (called left-associative), is evaluated from the left to the right. Most operators fall into this category. Similarly, an operator which associates to the right, is evaluated from the right to the left. Examples:
3-2-1 -> (3-2)-1 ; - is left-associative 3+2+1 -> (3+2)+1 ; + is left-associative a=b=c -> a=(b=c) ; = is right-associative
As you can see, this results in the desired behaviour. Suppose the - (subtraction) operator would associate from right to left, then the result of the first example would be 3-(2-1) = 2 instead of (3-2)-1 = 0. So you need to pay attention to associativity, or use excessive parentheses.
See Also
Variables