Precedence of Operators in C++

When writing complex expressions with several operands, we may have some doubts about which operand is
evaluated first and which later. For example, in this expression:
a = 5 + 7 % 2

we may doubt if it really means:
a = 5 + (7 % 2) // with a result of 6, or
a = (5 + 7) % 2 // with a result of 0
The correct answer is the first of the two expressions, with a result of 6. There is an established order with the
priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but
for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows:
Level Operator Description Grouping
1 :: scope
Left-toright
2
() [] . -> ++ -- dynamic_cast static_cast
reinterpret_cast const_cast typeid postfix
Left-toright
3
++ -- ~ ! sizeof new delete unary (prefix)
Right-toleft
* &
indirection and reference
(pointers)
+ - unary sign operator
4 (type) type casting
Right-toleft
5 .* ->* pointer-to-member
Left-toright
6 * / % multiplicative
Left-toright
7 + - additive
Left-toright
8 << >> shift
Left-toright
9 < > <= >= relational
Left-toright
10 == != equality
Left-toright
11 & bitwise AND
Left-toright
12 ^ bitwise XOR
Left-toright
13 | bitwise OR
Left-toright
14 && logical AND
Left-toright
15 || logical OR
Left-toright
16 ?: conditional
Right-toleft
17 = *= /= %= += -= >>= <<= &= ^= |= assignment
Right-toleft
18 , comma
Left-toright
Grouping defines the precedence order in which operators are evaluated in the case that there are several
operators of the same level in an expression.
All these precedence levels for operators can be manipulated or become more legible by removing possible
ambiguities using parentheses signs ( and ), as in this example:
a = 5 + 7 % 2;


might be written either as:
a = 5 + (7 % 2);
or
a = (5 + 7) % 2;
depending on the operation that we want to perform.
So if you want to write complicated expressions and you are not completely sure of the precedence levels, always
include parentheses. It will also become a code easier to read.


Learn More :