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

char * str = "Whoa";

char ch = *++str;

The prefix ++ operator and the unary * operator have the same precedence, but they associate right-to-left. So, again, str and not *str is incremented. Because the ++ operator is in prefix form, first str is incremented, and then the resulting pointer is dereferenced. Thus, str moves to point to the h character, and the h character is assigned to ch.

Note that Table D.1 uses binary or unary in the “Precedence” column to distinguish between two operators that use the same symbol, such as the unary address operator and the binary bitwise AND operator.

Appendix B, “C++ Reserved words,” lists alternative representations for some of the operators.

E. Other Operators

To avoid terminal obesity, the main text of this book doesn’t cover three groups of operators. The first group consists of the bitwise operators, which let you manipulate individual bits in a value; these operators were inherited from C. The second group consists of two-member dereferencing operators; they are C++ additions. The third group includes operators added by C++11: alignof and noexcept. This appendix briefly summarizes these operators.

Bitwise Operators

The bitwise operators operate on the bits of integer values. For example, the left-shift operator moves bits to the left, and the bitwise negation operator turns each 1 to a 0 and each 0 to a 1. Altogether, C++ has six such operators: <<, >>, ~, &, |, and ^.

The Shift Operators

The left-shift operator has the following syntax:

value << shift

Here value is the integer value to be shifted, and shift is the number of bits to shift. For example, the following shifts all the bits in the value 13 three places to the left:

13 << 3

The vacated places are filled with zeros, and bits shifted past the end are discarded (see Figure E.1).

Figure E.1. The left-shift operator.

Because each bit position represents a value twice that of the bit to the right (see Appendix A, “Number Bases”), shifting one bit position is equivalent to multiplying the value by 2. Similarly, shifting two bit positions is equivalent to multiplying by 22, and shifting n positions is equivalent to multiplying by 2n. Thus, the value of 13 << 3 is 13×23, or 104.

The left-shift operator provides a capability often found in assembly languages. However, an assembly language left-shift operator directly alters the contents of a register, whereas the C++ left-shift operator produces a new value without altering existing values. For example, consider the following:

int x = 20;

int y = x << 3;

This code doesn’t change the value of x. The expression x << 3 uses the value of x to produce a new value, much as x + 3 produces a new value without altering x.

If you want to use the left-shift operator to change the value of a variable, you must also use assignment. You can use regular assignment or the <<= operator, which combines shifting with assignment:

x = x << 4;           // regular assignment

y <<= 2;              // shift and assign

The right-shift operator (>>), as you might expect, shifts bits to the right. It has the following syntax:

value >> shift

Here value is the integer value to be shifted, and shift is the number of bits to shift. For example, the following shifts all the bits in the value 17 two places to the right:

17 >> 2

For unsigned integers, the vacated places are filled with zeros, and bits shifted past the end are discarded. For signed integers, vacated places may be filled with zeros or else with the value of the original leftmost bit. The choice depends on the C++ implementation. (Figure E.2 shows an example that illustrates filling with zeros.)

Figure E.2. The right-shift operator.

The right-shift operator. Shifting one place to the right is equivalent to integer division by 2. In general, shifting n places to the right is equivalent to integer division by 2n.

C++ also defines a right-shift-and-assign operator that you can use to replace the value of a variable by the shifted value:

int q = 43;

q >>= 2;            // replace 43 by 43 >> 2, or 10

On some systems, using left- and right-shift operators may produce faster integer multiplication and division by 2 than using the division operator, but as compilers get better at optimizing code, such differences are fading.

The Logical Bitwise Operators

The logical bitwise operators are analogous to the regular logical operators, except they apply to a value on a bit-by-bit basis rather than to the whole. For example, consider the regular negation operator (!) and the bitwise negation (or complement) operator (~). The ! operator converts a true (or nonzero) value to false and a false value to true. The ~ operator converts each individual bit to its opposite (1 to 0 and 0 to 1). For example, consider the unsigned char value of 3:

unsigned char x = 3;

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

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

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

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