Читаем C++ Primer Plus полностью

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

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

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

1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных