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

C++ defines the value of an assignment expression to be the value of the member on the left, so the expression has the value 20. The fact that assignment expressions have values permits statements such as the following:

maids = (cooks = 4) + 3;

The expression cooks = 4 has the value 4, so maids is assigned the value 7. However, just because C++ permits this behavior doesn’t mean you should encourage it. But the same rule that makes this peculiar statement possible also makes the following useful statement possible:

x = y = z = 0;

This is a fast way to set several variables to the same value. The precedence table (see Appendix D, “Operator Precedence”) reveals that assignment associates right-to-left, so first 0 is assigned to z, and then z = 0 is assigned to y, and so on.

Finally, as mentioned previously, relational expressions such as x < y evaluate to the bool values true or false. The short program in Listing 5.3 illustrates some points about expression values. The << operator has higher precedence than the operators used in the expressions, so the code uses parentheses to enforce the correct order.

Listing 5.3. express.cpp

// express.cpp -- values of expressions

#include

int main()

{

    using namespace std;

    int x;

    cout << "The expression x = 100 has the value ";

    cout << (x = 100) << endl;

    cout << "Now x = " << x << endl;

    cout << "The expression x < 3 has the value ";

    cout << (x < 3) << endl;

    cout << "The expression x > 3 has the value ";

    cout << (x > 3) << endl;

    cout.setf(ios_base::boolalpha);   //a newer C++ feature

    cout << "The expression x < 3 has the value ";

    cout << (x < 3) << endl;

    cout << "The expression x > 3 has the value ";

    cout << (x > 3) << endl;

    return 0;

}

Here is the output from the program in Listing 5.3:

The expression x = 100 has the value 100

Now x = 100

The expression x < 3 has the value 0

The expression x > 3 has the value 1

The expression x < 3 has the value false

The expression x > 3 has the value true

Normally, cout converts bool values to int before displaying them, but the cout.setf(ios::boolalpha) function call sets a flag that instructs cout to display the words true and false instead of 1 and 0.

Note

A C++ expression is a value or a combination of values and operators, and every C++ expression has a value.

To evaluate the expression x = 100, C++ must assign the value 100 to x. When the very act of evaluating an expression changes the value of data in memory, we say the evaluation has a side effect. Thus, evaluating an assignment expression has the side effect of changing the assignee’s value. You might think of assignment as the intended effect, but from the standpoint of how C++ is constructed, evaluating the expression is the primary effect. Not all expressions have side effects. For example, evaluating x + 15 calculates a new value, but it doesn’t change the value of x. But evaluating ++x + 15 does have a side effect because it involves incrementing x.

From expression to statement is a short step; you just add a semicolon. Thus, the following is an expression:

age = 100

Whereas the following is a statement:

age = 100;

More particularly, it is an expression statement. Any expression can become a statement if you add a semicolon, but the result might not make programming sense. For example, if rodents is a variable, then the following is a valid C++ statement:

rodents + 6;     // valid, but useless, statement

The compiler allows it, but the statement doesn’t accomplish anything useful. The program merely calculates the sum, does nothing with it, and goes on to the next statement. (A smart compiler might even skip the statement.)

Nonexpressions and Statements

Some concepts, such as knowing the structure of a for loop, are crucial to understanding C++. But there are also relatively minor aspects of syntax that can suddenly bedevil you just when you think you understand the language. We’ll look at a couple of them now.

Although it is true that adding a semicolon to any expression makes it a statement, the reverse is not true. That is, removing a semicolon from a statement does not necessarily convert it to an expression. Of the kinds of statements we’ve used so far, return statements, declaration statements, and for statements don’t fit the statement = expression + semicolon mold. For example, this is a statement:

int toad;

But the fragment int toad is not an expression and does not have a value. This makes code such as the following invalid:

eggs = int toad * 1000;   // invalid, not an expression

cin >> int toad;          // can't combine declaration with cin

Similarly, you can’t assign a for loop to a variable. In the following example, the for loop is not an expression, so it has no value and you can’t assign it:

int fx = for (i = 0; i< 4; i++)

     cout >> i;   // not possible

Bending the Rules

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

Все книги серии 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.

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

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