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 in this chapter provide a complete reference for each of these operators.

Expressions are evaluated according to the precedence and grouping of their operators. (Table 1.1 in Chapter 1, Lexical Conventions, shows the relationships the C++ operators impose on expressions.) Consider this example:

#include <iostream.h>

void main()
{
    int a = 2, b = 4, c = 9;

    cout << a + b * c << "\n";
    cout << a + (b * c) << "\n";
    cout << (a + b) * c << "\n";
}

The output from the preceding code is:

38
38
54

Figure 4.1   Expression-Evaluation Order

The order in which the expression shown in Figure 4.1 is evaluated is determined by the precedence and associativity of the operators:

  1. Multiplication (*) has the highest precedence in this expression; hence the subexpression b * c is evaluated first.

  2. Addition (+) has the next highest precedence, so a is added to the product of b and c.

  3. 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 Figure 4.2.

Figure 4.2   Expression-Evaluation Order with Parentheses

Expressions such as those in Figure 4.2 are evaluated purely for their side effects — in this case, to transfer information to the standard output device.

Note   The left-shift operator is used to insert an object in an object of class ostream. It is sometimes called the “insertion” operator when used with iostream.