Compound Assignment Operators

We often apply an operator to an object and then assign the result to that same object. As an example, consider the sum program from § 1.4.2 (p. 13):

int sum = 0;
// sum values from 1 through 10 inclusive
for (int val = 1; val <= 10; ++val)
    sum += val; //  equivalent to sum = sum + val

This kind of operation is common not just for addition but for the other arithmetic operators and the bitwise operators, which we cover in § 4.8 (p. 152). There are compound assignments for each of these operators:

 +=   -=   *=   /=   %=         // arithmetic operators
<<=  >>=   &=   ^=   |=         // bitwise operators; see § 4.8 (p. 152)

Each compound operator is essentially equivalent to

a = a op b;

with the exception that, when we use the compound assignment, the left-hand operand is evaluated only once. If we use an ordinary assignment, that operand is evaluated twice: once in the expression on the right-hand side and again as the operand on the left hand. In many, perhaps most, contexts this difference is immaterial aside from possible performance consequences.


Exercises Section 4.4

Exercise 4.13: What are the values of i and d after each assignment?

int i;   double d;

(a) d = i = 3.5;

(b) i = d = 3.5;

Exercise 4.14: Explain what happens in each of the if tests:

if (42 = i)   //  ...
if (i = 42)   //  ...

Exercise 4.15: The following assignment is illegal. Why? How would you correct it?

double dval; int ival; int *pi;
dval = ival = pi = 0;

Exercise 4.16: 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 (p = getPtr() != 0)

(b) if (i = 1024)


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.127.37