The value of an expression depends on how the subexpressions are grouped. For example, in the following expression, a purely left-to-right eva luation yields 20:
- 6 + 3 * 4 / 2 + 2;
Other imaginable results include 9, 14, and 36. In C++(www.cppentry.com), the result is 14.
Multiplication and division have higher precedence than addition. Their operands are bound to the operator in preference to the operands to addition. Multiplication and division have the same precedence as each other. Operators also have associativity, which determines how operators at the same precedence level are grouped. The arithmetic operators are left associative, which means they group left to right. We now can see that our expression is equivalent to
- int temp = 3 * 4; // 12
- int temp2 = temp / 2; // 6
Parentheses Override Precedence
We can override precedence with parentheses. Parenthesized expressions are eva luated by treating each parenthesized subexpression as a unit and otherwise applying the normal precedence rules. For example, we can use parentheses on our
initial expression to force the eva luation to result in any of the four possible values:
- // parentheses on this expression match default precedence/associativity
- cout << ((6 + ((3 * 4) / 2)) + 2) << endl; // prints 14
- // parentheses result in alternative groupings
- cout << (6 + 3) * (4 / 2 + 2) << endl; // prints 36
- cout << ((6 + 3) * 4) / 2 + 2 << endl; // prints 20
- cout << 6 + 3 * 4 / (2 + 2) << endl; // prints 9
We have already seen examples where precedence rules affect the correctness of our programs. For example, consider the expression described in the “Advice” box on page 164:
- *iter++;
Precedence says that ++ has higher precedence than *. That means that iter++ is grouped first. The operand of *, therefore, is the result of applying the increment operator to iter. If we wanted to increment the value that iter denotes, we’d have to use parentheses to force our intention:
- (*iter)++; // increment value to which iter refers and yield unincremented value
The parentheses specify that the operand of * is iter. The expression now uses
- *iter as the operand to ++.
As another example, recall the condition in the while on page 161:
- while ((i = get_value()) != 42) {
The parentheses around the assignment were necessary to implement the desired operation, which was to assign to i the value returned from get_value and then test that value to see whether it was 42. Had we failed to parenthesize the assignment, the effect would be to test the return value to see whether it was 42. The true or false value of that test would then be assigned to i, meaning that i would either be 1 or 0.