Order of Evaluation
This section discusses the order in which expressions are evaluated but does not explain the syntax or the semantics of the operators in these expressions. The earlier sections provide a complete reference for each of these operators.
Expressions are evaluated according to the precedence and grouping of their operators. (Operator Precedence and Associativity in Lexical Conventions, shows the relationships the C++ operators impose on expressions.) Consider this example:
Example
// expre_pluslang__pluslang_Order_of_Evaluation.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main()
{
int a = 2, b = 4, c = 9;
cout << a + b * c << "\n";
cout << a + (b * c) << "\n";
cout << (a + b) * c << "\n";
}
Output
38 38 54
Expression-Evaluation Order
The order in which the expression shown in the above figure is evaluated is determined by the precedence and associativity of the operators:
Multiplication (*) has the highest precedence in this expression; hence the subexpression b * c is evaluated first.
Addition (+) has the next highest precedence, so a is added to the product of b and c.
Left shift (<<) has the lowest precedence in the expression, but there are two occurrences. Because the left-shift operator groups left-to-right, the left subexpression is evaluated first and then the right one.
When parentheses are used to group the subexpressions, they alter the precedence and also the order in which the expression is evaluated, as shown in the following figure.
Expression-Evaluation Order with Parentheses
Expressions such as those in the above figure are evaluated purely for their side effects — in this case, to transfer information to the standard output device.