As you have seen, a block enables you to sneak two or more statements into a place where C++ syntax allows just one statement. The comma operator does the same for expressions, enabling you to sneak two expressions into a place where C++ syntax allows only one expression. For example, suppose you have a loop in which one variable increases by one each cycle and a second variable decreases by one each cycle. Doing both in the update part of a for loop control section would be convenient, but the loop syntax allows just one expression there. The solution is to use the comma operator to combine the two expressions into one:

++j, --i   // two expressions count as one for syntax purposes

The comma is not always a comma operator. For example, the comma in this declaration serves to separate adjacent names in a list of variables:

int i, j;  // comma is a separator here, not an operator

Listing 5.9 uses the comma operator twice in a program that reverses the contents of a string class object. (You could also write the program by using an array of char, but the length of the word would be limited by your choice of array size.) Note that Listing 5.6 displays the contents of an array in reverse order, but Listing 5.9 actually moves characters around in the array. The program in Listing 5.9 also uses a block to group several statements into one.

Listing 5.9. forstr2.cpp

// forstr2.cpp -- reversing an array

#include

#include

int main()

{

    using namespace std;

    cout << "Enter a word: ";

    string word;

    cin >> word;

    // physically modify string object

    char temp;

    int i, j;

    for (j = 0, i = word.size() - 1; j < i; --i, ++j)

    {                       // start block

        temp = word[i];

        word[i] = word[j];

        word[j] = temp;

    }                       // end block

    cout << word << "\nDone\n";

    return 0;

}

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

Enter a word: stressed

desserts

Done

By the way, the string class offers more concise ways to reverse a string, but we’ll leave those for Chapter 16, “The string Class and the Standard Template Library.”

Program Notes

Look at the for control section of the program in Listing 5.9. First, it uses the comma operator to squeeze two initializations into one expression for the first part of the control section. Then it uses the comma operator again to combine two updates into a single expression for the last part of the control section.

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

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

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