Determine the Order of Operations in C++
All operators perform some defined function in C++. In addition, every operator has a precedence — a specified order in which the expressions are evaluated. Consider, for example, how precedence affects solving the following problem:
int var = 2 * 3 + 1;
If the addition is performed before the multiplication, the value of the expression is 2 times 4, or 8. If the multiplication is performed first, the value is 6 plus 1, or 7.
The precedence of the operators determines who goes first. The concept of precedence is also present in arithmetic. C++ adheres to the common arithmetic precedence. Therefore, multiplication has higher precedence than addition, so the result is 7.
So what happens when two operators of the same precedence appear in the same expression? For example:
int var = 8 / 4 / 2;
When operators of the same precedence appear in the same expression, they are evaluated from left to right (the same rule applied in arithmetic). Thus, in this code snippet, var is equal to 8 divided by 4 (which is 2) divided by 2 (which is 1).
x / 100 + 32
divides x by 100 before adding 32. But what if the programmer wanted to divide x by 100 plus 32? The programmer can change the precedence by bundling expressions together in parentheses (shades of algebra!), as follows:
x /(100 + 32)
This expression has the same effect as dividing x by 132. The original expression
x / 100 + 32
is identical to the expression
(x / 100) + 32