C++ Operator Precedence
The operators at the top of this list are evaluated first.
Precedence | Operator | Description | Example | Associativity |
1 | :: | Scoping operator | Class::age = 2; | none |
2 | () | Grouping operator | (a + b) / 4; | left to right |
3 | ! | Logical negation | if( !done ) ... | right to left |
4 | ->* | Member pointer selector | ptr->*var = 24; | left to right |
5 | * | Multiplication | int i = 2 * 4; | left to right |
6 | + | Addition | int i = 2 + 3; | left to right |
7 | << | Bitwise shift left | int flags = 33 << 1; | left to right |
8 | < | Comparison less-than | if( i < 42 ) ... | left to right |
9 | == | Comparison equal-to | if( i == 42 ) ... | left to right |
10 | & | Bitwise AND | flags = flags & 42; | left to right |
11 | ^ | Bitwise exclusive OR | flags = flags ^ 42; | left to right |
12 | | | Bitwise inclusive (normal) OR | flags = flags | 42; | left to right |
13 | && | Logical AND | if( conditionA && conditionB ) ... | left to right |
14 | || | Logical OR | if( conditionA || conditionB ) ... | left to right |
15 | ? : | Ternary conditional (if-then-else) | int i = (a > b) ? a : b; | right to left |
16 | = | Assignment operator | int a = b; | right to left |
17 | , | Sequential evaluation operator | for( i = 0, j = 0; i < 10; i++, j++ ) ... | left to right |
One important aspect of C++ that is related to operator precedence is the order of evaluation and the order of side effects in expressions. In some circumstances, the order in which things happen is not defined. For example, consider the following code:
float x = 1;
x = x / ++x;
The value of x is not guaranteed to be consistent across different compilers, because it is not clear whether the computer should evaluate the left or the right side of the division first. Depending on which side is evaluated first, x could take a different value.
Furthermore, while ++x
evaluates to x+1
, the side effect of actually storing that new value in x could happen at different times, resulting in different values for x.
The bottom line is that expressions like the one above are horribly ambiguous and should be avoided at all costs. When in doubt, break a single ambiguous expression into multiple expressions to ensure that the order of evaluation is correct.