Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 62

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 62 страницаB. Stroustrup - The C++ Programming Language (794319) страница 622019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 62)

More precisely, the resultis the least unsigned integer congruent to the source integer modulo 2 to the nth, where n is thenumber of bits used to represent the unsigned type. For example:unsigned char uc = 1023;// binary 1111111111: uc becomes binary 11111111, that is, 255If the destination type is signed, the value is unchanged if it can be represented in the destinationtype; otherwise, the value is implementation-defined:signed char sc = 1023;// implementation-definedPlausible results are 127 and −1 (§6.2.3).A Boolean or plain enumeration value can be implicitly converted to its integer equivalent(§6.2.2, §8.4).Section 10.5.2.2Floating-Point Conversions26910.5.2.2 Floating-Point ConversionsA floating-point value can be converted to another floating-point type.

If the source value can beexactly represented in the destination type, the result is the original numeric value. If the sourcevalue is between two adjacent destination values, the result is one of those values. Otherwise, thebehavior is undefined. For example:float f = FLT_MAX;double d = f;// largest float value// OK: d == fdouble d2 = DBL_MAX; // largest double valuefloat f2 = d2;// undefined if FLT_MAX<DBL_MAXlong double ld = d2;// OK: ld = d3long double ld2 = numeric_limits<long double>::max();double d3 = ld2;// undefined if sizeof(long double)>sizeof(double)DBL_MAXand FLT_MAX are defined in <climits>; numeric_limits is defined in <limits> (§40.2).10.5.2.3 Pointer and Reference ConversionsAny pointer to an object type can be implicitly converted to a void∗ (§7.2.1). A pointer (reference)to a derived class can be implicitly converted to a pointer (reference) to an accessible and unambiguous base (§20.2).

Note that a pointer to function or a pointer to member cannot be implicitlyconverted to a void∗.A constant expression (§10.4) that evaluates to 0 can be implicitly converted to a null pointer ofany pointer type. Similarly, a constant expression that evaluates to 0 can be implicitly converted toa pointer-to-member type (§20.6). For example:int∗ p = (1+2)∗(2∗(1−1)); // OK, but weirdPrefer nullptr (§7.2.2).A T∗ can be implicitly converted to averted to a const T&.const T∗(§7.5).

Similarly, aT&can be implicitly con-10.5.2.4 Pointer-to-Member ConversionsPointers and references to members can be implicitly converted as described in §20.6.3.10.5.2.5 Boolean ConversionsPointer, integral, and floating-point values can be implicitly converted tovalue converts to true; a zero value converts to false. For example:void f(int∗ p, int i){bool is_not_zero = p;bool b2 = i;// ...}// true if p!=0// true if i!=0bool(§6.2.2). A nonzero270ExpressionsChapter 10The pointer-to-bool conversion is useful in conditions, but confusing elsewhere:void fi(int);void fb(bool);void ff(int∗ p, int∗ q){if (p) do_something(∗p);// OKif (q!=nullptr) do_something(∗q); // OK, but verbose// ...fi(p);// error : no pointer to int conversionfb(p);// OK: pointer to bool conversion (surprise!?)}Hope for a compiler warning for fb(p).10.5.2.6 Floating-Integral ConversionsWhen a floating-point value is converted to an integer value, the fractional part is discarded.

Inother words, conversion from a floating-point type to an integer type truncates. For example, thevalue of int(1.6) is 1. The behavior is undefined if the truncated value cannot be represented in thedestination type. For example:int i = 2.7;char b = 2000.7;// i becomes 2// undefined for 8-bit chars: 2000 cannot be represented as an 8-bit charConversions from integer to floating types are as mathematically correct as the hardware allows.Loss of precision occurs if an integral value cannot be represented exactly as a value of the floatingtype.

For example:int i = float(1234567890);On a machine where both ints and floats are represented using 32 bits, the value of i is 1234567936.Clearly, it is best to avoid potentially value-destroying implicit conversions. In fact, compilerscan detect and warn against some obviously dangerous conversions, such as floating to integral andlong int to char. However, general compile-time detection is impractical, so the programmer mustbe careful. When ‘‘being careful’’ isn’t enough, the programmer can insert explicit checks. Forexample:char checked_cast(int i){char c = i;// warning: not portable (§10.5.2.1)if (i != c) throw std::runtime_error{"int−to−char check failed"};return c;}void my_code(int i){char c = checked_cast(i);// ...}Section 10.5.2.6Floating-Integral Conversions271A more general technique for expressing checked conversions is presented in §25.2.5.1.To truncate in a way that is guaranteed to be portable requires the use of numeric_limits (§40.2).In initializations, truncation can be avoided by using the {}-initializer notation (§6.3.5).10.5.3 Usual Arithmetic ConversionsThese conversions are performed on the operands of a binary operator to bring them to a commontype, which is then used as the type of the result:[1] If either operand is of type long double, the other is converted to long double.• Otherwise, if either operand is double, the other is converted to double.• Otherwise, if either operand is float, the other is converted to float.• Otherwise, integral promotions (§10.5.1) are performed on both operands.[2] Otherwise, if either operand is unsigned long long, the other is converted to unsigned longlong.• Otherwise, if one operand is a long long int and the other is an unsigned long int, thenif a long long int can represent all the values of an unsigned long int, the unsigned longint is converted to a long long int; otherwise, both operands are converted to unsignedlong long int.

Otherwise, if either operand is unsigned long long, the other is convertedto unsigned long long.• Otherwise, if one operand is a long int and the other is an unsigned int, then if a longint can represent all the values of an unsigned int, the unsigned int is converted to along int; otherwise, both operands are converted to unsigned long int.• Otherwise, if either operand is long, the other is converted to long.• Otherwise, if either operand is unsigned, the other is converted to unsigned.• Otherwise, both operands are int.These rules make the result of converting an unsigned integer to a signed one of possibly larger sizeimplementation-defined.

That is yet another reason to avoid mixing unsigned and signed integers.10.6 Advice[1][2][3][4]Prefer the standard library to other libraries and to ‘‘handcrafted code’’; §10.2.8.Use character-level input only when you have to; §10.2.3.When reading, always consider ill-formed input; §10.2.3.Prefer suitable abstractions (classes, algorithms, etc.) to direct use of language features (e.g.,ints, statements); §10.2.8.[5] Avoid complicated expressions; §10.3.3.[6] If in doubt about operator precedence, parenthesize; §10.3.3.[7] Avoid expressions with undefined order of evaluation; §10.3.2.[8] Avoid narrowing conversions; §10.5.2.[9] Define symbolic constants to avoid ‘‘magic constants’’; §10.4.1.[10] Avoid narrowing conversions; §10.5.2.This page intentionally left blank11Select OperationsWhen someone says“I want a programming language in whichI need only say what I wish done,”give him a lollipop.– Alan Perlis••••••Etc. OperatorsLogical Operators; Bitwise Logical Operators; Conditional Expressions; Increment andDecrementFree StoreMemory Management; Arrays; Getting Memory Space; Overloading newListsImplementation Model; Qualified Lists; Unqualified ListsLambda ExpressionsImplementation Model; Alternatives to Lambdas; Capture; Call and Return; The Type of aLambdaExplicit Type ConversionConstruction; Named Casts; C-Style Cast; Function-Style CastAdvice11.1 Etc.

OperatorsThis section examines a mixed bag of simple operators: logical operators (&&, ||, and !), bitwise logical operators (&, |, ˜, <<, and >>), conditional expressions (?:), and increment and decrement operators (++ and −−). They have little in common beyond their details not fitting elsewhere in the discussions of operators.274Select OperationsChapter 1111.1.1 Logical OperatorsThe logical operators && (and), || (or), and ! (not) take operands of arithmetic and pointer types,convert them to bool, and return a bool result. The && and || operators evaluate their second argument only if necessary, so they can be used to control evaluation order (§10.3.2).

For example:while (p && !whitespace(∗p)) ++p;Here, p is not dereferenced if it is the nullptr.11.1.2 Bitwise Logical OperatorsThe bitwise logical operators & (and), | (or), ˆ (exclusive or, xor), ˜ (complement), >> (right shift),and << (left shift) are applied to objects of integral types – that is, char, short, int, long, long longand their unsigned counterparts, and bool, wchar_t, char16_t, and char32_t. A plain enum (but not anenum class) can be implicitly converted to an integer type and used as an operand to bitwise logicaloperations.

The usual arithmetic conversions (§10.5.3) determine the type of the result.A typical use of bitwise logical operators is to implement the notion of a small set (a bit vector).In this case, each bit of an unsigned integer represents one member of the set, and the number ofbits limits the number of members. The binary operator & is interpreted as intersection, | as union, ˆas symmetric difference, and ˜ as complement. An enumeration can be used to name the membersof such a set.

Характеристики

Тип файла
PDF-файл
Размер
18,76 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее