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

But what if you name the variable in the inner block teledeli instead of websight so that you have two variables of the same name, with one in the outer block and one in the inner block? In this case, the program interprets the teledeli name to mean the local block variable while the program executes statements within the block. We say the new definition hides the prior definition. The new definition is in scope, and the old definition is temporarily out of scope. When the program leaves the block, the original definition comes back into scope (see Figure 9.2).

Figure 9.2. Blocks and scope.

Listing 9.4 illustrates how automatic variables are localized to the functions or blocks that contain them.

Listing 9.4. autoscp.cpp

// autoscp.cpp -- illustrating scope of automatic variables

#include

void oil(int x);

int main()

{

    using namespace std;

    int texas = 31;

    int year = 2011;

    cout << "In main(), texas = " << texas << ", &texas = ";

    cout << &texas << endl;

    cout << "In main(), year = " << year << ", &year = ";

    cout << &year << endl;

    oil(texas);

    cout << "In main(), texas = " << texas << ", &texas = ";

    cout << &texas << endl;

    cout << "In main(), year = " << year << ", &year = ";

    cout << &year << endl;

    return 0;

}

void oil(int x)

{

    using namespace std;

    int texas = 5;

    cout << "In oil(), texas = " << texas << ", &texas = ";

    cout << &texas << endl;

    cout << "In oil(), x = " << x << ", &x = ";

    cout << &x << endl;

    {                               // start a block

        int texas = 113;

        cout << "In block, texas = " << texas;

        cout << ", &texas = " << &texas << endl;

                cout << "In block, x = " << x << ", &x = ";

        cout << &x << endl;

    }                               // end a block

    cout << "Post-block texas = " << texas;

    cout << ", &texas = " << &texas << endl;

}

Here is the output from the program in Listing 9.4:

In main(), texas = 31, &texas = 0012FED4

In main(), year = 2011, &year = 0012FEC8

In oil(), texas = 5, &texas = 0012FDE4

In oil(), x = 31, &x = 0012FDF4

In block, texas = 113, &texas = 0012FDD8

In block, x = 31, &x = 0012FDF4

Post-block texas = 5, &texas = 0012FDE4

In main(), texas = 31, &texas = 0012FED4

In main(), year = 2011, &year = 0012FEC8

Notice that each of the three texas variables in Listing 9.4 has its own distinct address and that the program uses only the particular variable in scope at the moment, so assigning the value 113 to the texas in the inner block in oil() has no effect on the other variables of the same name. (As usual, the actual address values and address format will differ from system to system.)

Let’s summarize the sequence of events. When main() starts, the program allocates space for texas and year, and these variables come into scope. When the program calls oil(), these variables remain in memory but pass out of scope. Two new variables, x and texas, are allocated and come into scope. When program execution reaches the inner block in oil(), the new texas passes out of scope (is hidden) because it is superseded by an even newer definition. The variable x, however, stays in scope because the block doesn’t define a new x. When execution exits the block, the memory for the newest texas is freed, and texas #2 comes back into scope. When the oil() function terminates, that texas and x expire, and the original texas and year come back into scope.

Changes to auto in C++11

In C++11, the keyword auto is used for automatic type deduction, as you have seen in Chapters 3, 7, and 8. But in C and in prior versions of C++, auto has an entirely different meaning. It’s used to explicitly identify a variable as having automatic storage:

int froob(int n)

{

     auto float ford;  // ford has automatic storage

     ...

}

Because programmers can use the auto keyword only with variables that are already automatic by default, they rarely bother using it. Its main function is to document that you really wanted to use a local automatic variable.

In C++11, this usage no longer is valid. The people who prepare standards are reluctant to introduce new keywords because doing so might invalidate existing code that already uses that word for other purposes. In this case, it was felt that the old use of auto was rare enough that it was better to repurpose this keyword rather than introduce a new one.

Initialization of Automatic Variables

You can initialize an automatic variable with any expression whose value will be known when the declaration is reached. The following example shows the variables x, big, y, and z being initialized:

int w;          // value of w is indeterminate

int x = 5;      // initialized with a numeric literal

int big = INT_MAX – 1; // initialized with a constant expression

int y = 2 * x;  // use previously determined value of x

cin >> w;

int z = 3 * w;  // use new value of w

Automatic Variables and the Stack

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

Все книги серии 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 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

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

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

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

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

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