# Precedence of Operators In C++

0
2
Writing complex expressions with more than a one operands, we may have a number of misgivings about which operand is evaluated foremost and which afterward.

For example, in this appearance:

i = 4 + 3% 2

we may hesitation if it actually means:

i = 4+ (3% 2)
i = (4 + 3) % 2

The right answer is the first of the two expressions, with i answer of 5.

There is an established order with the precedence of each operator, and not only the arithmetic ones 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-to-right
2 () [] . -> ++ — dynamic_cast static_cast reinterpret_cast const_cast typeid postfix Left-to-right
3 ++ — ~ ! sizeof new delete

*&

+-

 unary (prefix)

indirection and reference (pointers)

unary sign operator

Right-to-left
4 (type) type casting Right-to-left
5 .&->* pointer-to-member Left-to-right
6 */% multiplicative Left-to-right
7 +-
Left-to-right
8 <<>> shift Left-to-right
9 <><= >= relational Left-to-right
10 == != equality Left-to-right
11 & bitwise AND Left-to-right
12 ^
 bitwise XOR
Left-to-right
13 l bitwise OR Left-to-right
14 && logical AND Left-to-right
15 ll logical OR Left-to-right
16 ?: conditional Right-to-left
17
 = *= /= %= += -= >>= <<= &= ^= !=
assignment Right-to-left
18 , comma Left-to-right

i = 4 + 3% 2;

might be written either as:

i = 4 + (3 % 2);
Or
i = (4 + 3) % 2;

depending on the operation that we want to perform.