|
Associativity specifies how to group operators at the same precedence level. We have also seen cases where associativity matters. As one example, the assignment operator is right associative. This fact allows concatenated assignments: - ival = jval = kval = lval
- (ival = (jval = (kval = lval)))
This expression first assigns lval to kval, then the result of that to jval, and finally the result of that to ival.
The arithmetic operators, on the other hand, are left associative. The expression - ival * jval / kval * lval
- (((ival * jval) / kval) * lval)
multiplies ival and jval, then divides that result by kval, and finally multiplies the result of the division by lval.
Table 5.4 presents the full set of operators ordered by precedence. The table is organized into segments separated by double lines. Operators in each segment have the same precedence, and have higher precedence than operators in subsequent segments. For example, the prefix increment and dereference operators share the same precedence and have higher precedence than the arithmetic or relational operators. We have seen most of these operators, although a few will not be defined until later chapters.
EXERCISES SECTION 5.10.2
Exercise 5.25: Using Table 5.4 (p. 170), parenthesize the following expressions to indicate the order in which the operands are grouped:
(a) ! ptr == ptr->next
(b) ch = buf[ bp++ ] != ’\n’
Exercise 5.26: The expressions in the previous exercise eva luate in an order that is likely to be surprising. Parenthesize these expressions to eva luate in an order you imagine is intended.
Exercise 5.27: The following expression fails to compile due to operator precedence. Using Table 5.4 (p. 170), explain why it fails. How would you fix it - string s = "word";
-
- string pl = s + s[s.size() - 1] == ’s’ "" : "s" ;
|