Selections in C++: Operator Precedence and Associativity

Operator precedence and associativity determine the order in which operators are evaluated.

Section 2.9, “Evaluating Expressions and Operator Precedence,” introduced operator prec­-edence involving arithmetic operators. This section discusses operator precedence in more details. Suppose that you have the following expression:

3 + 4 * 4 > 5 * (4 + 3) – 1 && (4 3 > 5)

What is its value? What is the execution order of the operators?

The expression in the parentheses is evaluated first. (Parentheses can be nested, in which case the expression in the inner parentheses is executed first.) When evaluating an expres­sion without parentheses, the operators are applied according to the precedence rule and the associativity rule.

The precedence rule defines precedence for operators, as shown in Table 3.7, which con­tains the operators you have learned so far. Operators are listed in decreasing order of prec­edence from top to bottom. The logical operators have lower precedence than the relational operators and the relational operators have lower precedence than the arithmetic operators. Operators with the same precedence appear in the same group. (See Appendix C, Operator Precedence Chart, for a complete list of C++ operators and their precedence.)

If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left associative. For example, since + and – are of the same precedence and are left associative, the expression

Assignment operators are right associative. Therefore, the expression

Suppose a, b, and c are 1 before the assignment; after the whole expression is evaluated, a becomes 6, b becomes 6, and c becomes 5. Note that left associativity for the assignment operator would not make sense.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *