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

Compound Statements, or Blocks

The format, or syntax, for writing a C++ for statement might seem restrictive to you because the body of the loop must be a single statement. That’s awkward if you want the loop body to contain several statements. Fortunately, C++ provides a syntax loophole through which you may stuff as many statements as you like into a loop body. The trick is to use paired braces to construct a compound statement, or block. The block consists of paired braces and the statements they enclose and, for the purposes of syntax, counts as a single statement. For example, the program in Listing 5.8 uses braces to combine three separate statements into a single block. This enables the body of the loop to prompt the user, read input, and do a calculation. The program calculates the running sum of the numbers you enter, and this provides a natural occasion for using the += operator.

Listing 5.8. block.cpp

// block.cpp -- use a block statement

#include

int main()

{

    using namespace std;

    cout << "The Amazing Accounto will sum and average ";

    cout << "five numbers for you.\n";

    cout << "Please enter five values:\n";

    double number;

    double sum = 0.0;

    for (int i = 1; i <= 5; i++)

    {                                   // block starts here

        cout << "Value " << i << ": ";

        cin >> number;

        sum += number;

    }                                   // block ends here

    cout << "Five exquisite choices indeed! ";

    cout << "They sum to " << sum << endl;

    cout << "and average to " << sum / 5 << ".\n";

    cout << "The Amazing Accounto bids you adieu!\n";

    return 0;

}

Here is a sample run of the program in Listing 5.8:

The Amazing Accounto will sum and average five numbers for you.

Please enter five values:

Value 1: 1942

Value 2: 1948

Value 3: 1957

Value 4: 1974

Value 5: 1980

Five exquisite choices indeed! They sum to 9801

and average to 1960.2.

The Amazing Accounto bids you adieu!

Suppose you leave in the indentation but omit the braces:

for (int i = 1; i <= 5; i++)

      cout << "Value " << i << ": ";      // loop ends here

      cin >> number;                      // after the loop

      sum += number;

cout << "Five exquisite choices indeed! ";

The compiler ignores indentation, so only the first statement would be in the loop. Thus, the loop would print the five prompts and do nothing more. After the loop completes, the program moves to the following lines, reading and summing just one number.

Compound statements have another interesting property. If you define a new variable inside a block, the variable persists only as long as the program is executing statements within the block. When execution leaves the block, the variable is deallocated. That means the variable is known only within the block:

#include  

int main()

{

    using namespace std;

    int x = 20;

    {                       // block starts

        int y = 100;

        cout << x << endl;  // ok

        cout << y << endl;  // ok

    }                       // block ends

    cout << x << endl;      // ok

    cout << y << endl;      // invalid, won't compile

    return 0;

Note that a variable defined in an outer block is still defined in the inner block.

What happens if you declare a variable in a block that has the same name as one outside the block? The new variable hides the old one from its point of appearance until the end of the block. Then the old one becomes visible again, as in this example:

#include

int main()

{

    using std::cout;

    using std::endl;

    int x = 20;             // original x

    {                       // block starts

        cout << x << endl;  // use original x

        int x = 100;        // new x

        cout << x << endl;  // use new x

    }                       // block ends

    cout << x << endl;      // use original x

    return 0;

}

More Syntax Tricks—The Comma Operator

Перейти на страницу:

Все книги серии Developer's Library

Похожие книги