Operator Precedence
When given a complex expression of operations, the compiler must know how to interpret these in the correct order as a different order of operation may result in vastly different results. Take this simple example 4 + 3 * 2 if we perform the addition first we calculate the sum of 4 and 3, resulting in 7, then we multiply that answer by 2 giving us a final result of 14. If we take the same expression but perform the multiplication of 3 and 2 first resulting in 6, then use that answer in our addition with 4 this gives us a final result of 10.
To avoid this problem, every programming language has a strict definition on how it determines the order of operation. Below is a table which shows the order of operations which is depending on the types of operators and the order in which they appear in the expression, the top of the table represents the operations performed first with the bottom representing operations which are performed last. All items within a single group have equivalent precedence, in these cases the order is simply as "left-to-right" or "right-to-left" depending on the specific group.
There are a number of items in the below table which have not yet been covered by our tutorials, but they will be revealed as we progress.
Group Precedence |
Operator | Description | Precedence Within A Group |
---|---|---|---|
1 |
:: |
Scope resolution | Left-to-right |
2 |
a++ a-- |
Postfix increment and decrement | |
a() Type() Type{} |
Function call or type constructor | ||
a[] |
Index operator | ||
. -> |
Member Access | ||
3 |
++a --a |
Prefix increment and decrement | Right-to-left |
+a -a |
Unary plus and minus | ||
! ~ |
Logical and bitwise NOT | ||
(type) |
C-style cast | ||
*a |
Pointer dereference | ||
&a |
Address-of | ||
sizeof |
sizeof language feature |
||
new new[] |
Dynamic memory management | ||
4 |
.* ->* |
Pointer to a member | Left-to-right |
5 |
a*b a/b a%b |
Multuplication, division and modulus | |
6 |
a+b a-b |
Addition and subtraction | |
7 |
<< >> |
Bitwise left and right shift | |
9 |
< <= |
Relational Comparison | |
10 |
== != |
Equality Comparison | |
11 |
& |
Bitwise AND | |
12 |
^ |
Bitwise XOR (exclusive or) | |
13 |
| |
Bitwise OR (inclusive or) | |
14 |
&& |
Logical AND | |
15 |
|| |
Logical OR | |
16 |
a?b:c |
Ternary comparison | Right-to-left |
throw |
Language feature: throw | ||
= += -= *= /= %= <<= >>= &= ^= |= |
Assignment and compound assignment | ||
17 |
, |
Comma | Left-to-right |