|
We often apply an operator to an object and then reassign the result to that same object. As an example, consider the sum program from page 14: - int sum = 0;
-
for (int val = 1; val <= 10; ++val) sum += val;
This kind of operation is common not just for addition but for the other arithmetic operators and the bitwise operators. There are compound assignments for each of these operators. The general syntactic form of a compound assignment operator is - a op= b;
where op= may be one of the following ten operators: - += -= *= /= %=
- <<= >>= &= ^= |=
Each compound operator is essentially equivalent to - a = a op b;
There is one important difference: When we use the compound assignment, the left-hand operand is eva luated only once. If we write the similar longer version, that operand is eva luated twice: once as the right-hand operand and again as the left. In many, perhaps most, contexts this difference is immaterial aside from possible performance consequences.
注意:复合赋值操作符不包括“ 逻辑与(&&)”和“ 逻辑或(||)”, 即 a =a && b 不能写成a &&= b。另外,等号之前不能有空格。
EXERCISES SECTION 5.4.3
Exercise 5.13: The following assignment is illegal. Why How would you correct it - double dval; int ival; int *pi;
- dval = ival = pi = 0;
Exercise 5.14: Although the following are legal, they probably do not behave as the programmer expects. Why Rewrite the expressions as you think they should be.
(a) if (ptr = retrieve_pointer() != 0) (b) if (ival = 1024) (c) ival += ival + 1;
|