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-to-right
2 () [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid postfix Left-to-right
3 ++ -- ~ ! sizeof new delete * & + - unary (prefix) Right-to-left
4 (type) type casting Right-to-left
5 .* ->* pointer-to-member Left-to-right
6 * / % multiplicative Left-to-right
7 + - additive 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 | bitwise OR Left-to-right
14 && logical AND Left-to-right
15 || logical OR Left-to-right
16 ?: conditional Right-to-left
17 = *= /= %= += -= >>= <<= &= ^= |= assignment Right-to-left
18 , comma Left-to-right

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.

// Precedence of Operators
#include <iostream>
using namespace std;

int main(){
  int a = 5 + 7 % 2; 
  int b = (5 + 7) % 2; 

  cout << "Result of 5 + 7 % 2: " << a << endl;
  cout << "Result of (5 + 7) % 2: " << b << endl;

  return 0;
}

The output of the code above will be: 6 and 0 because the first expression evaluates 5 + (7 % 2) while the second evaluates (5 + 7) % 2.

Now that you have learned about how Precedence of Operators work in C++ programming. Lets learn something about Input and Output in C++ in the next section.