Combination Assignment Operators

Listing 5.5 uses the following expression to update a loop counter:

i = i + by

C++ has a combined addition and assignment operator that accomplishes the same result more concisely:

i += by

The += operator adds the values of its two operands and assigns the result to the operand on the left. This implies that the left operand must be something to which you can assign a value, such as a variable, an array element, a structure member, or data you identify by dereferencing a pointer:

int k = 5;
k += 3;                  // ok, k set to 8
int *pa = new int[10];   // pa points to pa[0]
pa[4] = 12;
pa[4] += 6;              // ok, pa[4] set to 18
*(pa + 4) += 7;          // ok, pa[4] set to 25
pa += 2;                 // ok, pa points to the former pa[2]
34 += 10;                // quite wrong

Each arithmetic operator has a corresponding assignment operator, as summarized in Table 5.1. Each operator works analogously to +=. Thus, for example, the following statement replaces the current value of k with a value 10 times greater:

k *= 10;

Table 5.1. Combined Assignment Operators

Image

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

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