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

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

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

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

The remaining fundamental types are variations foroptimizations, special needs, and compatibility that are best ignored until such needs arise.6.2.2 BooleansA Boolean, bool, can have one of the two valuesresults of logical operations. For example:trueorfalse.A Boolean is used to express thevoid f(int a, int b){bool b1 {a==b};// ...}If a and b have the same value, b1 becomes true; otherwise, b1 becomes false.A common use of bool is as the type of the result of a function that tests some condition (a predicate).

For example:bool is_open(File∗);bool greater(int a, int b) { return a>b; }By definition, true has the value 1 when converted to an integer and false has the value 0. Conversely, integers can be implicitly converted to bool values: nonzero integers convert to true and 0converts to false. For example:bool b1 = 7;bool b2 {7};// 7!=0, so b becomes true// error: narrowing (§2.2.2, §10.5)int i1 = true;int i2 {true};// i1 becomes 1// i2 becomes 1If you prefer to use the {}-initializer syntax to prevent narrowing, yet still want to convert an int to abool, you can be explicit:140Types and DeclarationsChapter 6void f(int i){bool b {i!=0};// ...};In arithmetic and logical expressions, bools are converted to ints; integer arithmetic and logicaloperations are performed on the converted values.

If the result needs to be converted back to bool,a 0 is converted to false and a nonzero value is converted to true. For example:bool a = true;bool b = true;bool x = a+b;bool y = a||b;bool z = a−b;// a+b is 2, so x becomes true// a||b is 1, so y becomes true ("||" means "or")// a-b is 0, so z becomes falseA pointer can be implicitly converted to a bool (§10.5.2.5).

A non-null pointer converts topointers with the value nullptr convert to false. For example:void g(int∗ p){bool b = p;bool b2 {p!=nullptr};true;// narrows to true or false// explicit test against nullptrif (p) {// equivalent to p!=nullptr// ...}}I prefer if (p) over if (p!=nullptr) because it more directly expresses the notion ‘‘if p is valid’’ and alsobecause it is shorter. The shorter form leaves fewer opportunities for mistakes.6.2.3 Character TypesThere are many character sets and character set encodings in use. C++ provides a variety of character types that reflect that – often bewildering – variety:• char: The default character type, used for program text.

A char is used for the implementation’s character set and is usually 8 bits.• signed char: Like char, but guaranteed to be signed, that is, capable of holding both positiveand negative values.• unsigned char: Like char, but guaranteed to be unsigned.• wchar_t: Provided to hold characters of a larger character set such as Unicode (see §7.3.2.2).The size of wchar_t is implementation-defined and large enough to hold the largest characterset supported by the implementation’s locale (Chapter 39).• char16_t: A type for holding 16-bit character sets, such as UTF-16.• char32_t: A type for holding 32-bit character sets, such as UTF-32.These are six distinct types (despite the fact that the _t suffix is often used to denote aliases; §6.5).On each implementation, the char type will be identical to that of either signed char or unsignedSection 6.2.3Character Types141char,but these three names are still considered separate types.A char variable can hold a character of the implementation’s character set.

For example:char ch = 'a';Almost universally, a char has 8 bits so that it can hold one of 256 different values. Typically, thecharacter set is a variant of ISO-646, for example ASCII, thus providing the characters appearingon your keyboard. Many problems arise from the fact that this set of characters is only partiallystandardized.Serious variations occur between character sets supporting different natural languages andbetween character sets supporting the same natural language in different ways.

Here, we are interested only in how such differences affect the rules of C++. The larger and more interesting issue ofhow to program in a multilingual, multi-character-set environment is beyond the scope of this book,although it is alluded to in several places (§6.2.3, §36.2.1, Chapter 39).It is safe to assume that the implementation character set includes the decimal digits, the 26alphabetic characters of English, and some of the basic punctuation characters. It is not safe toassume that:• There are no more than 127 characters in an 8-bit character set (e.g., some sets provide 255characters).• There are no more alphabetic characters than English provides (most European languagesprovide more, e.g., æ, þ, and ß).• The alphabetic characters are contiguous (EBCDIC leaves a gap between 'i' and 'j').• Every character used to write C++ is available (e.g., some national character sets do not provide {, }, [, ], |, and \).• A char fits in 1 byte.

There are embedded processors without byte accessing hardware forwhich a char is 4 bytes. Also, one could reasonably use a 16-bit Unicode encoding for thebasic chars.Whenever possible, we should avoid making assumptions about the representation of objects. Thisgeneral rule applies even to characters.Each character has an integer value in the character set used by the implementation.

For example, the value of 'b' is 98 in the ASCII character set. Here is a loop that outputs the the integer valueof any character you care to input:void intval(){for (char c; cin >> c; )cout << "the value of '" << c << "' is " << int{c} << '\n';}The notation int{c} gives the integer value for a character c (‘‘the int we can construct from c’’).The possibility of converting a char to an integer raises the question: is a char signed or unsigned?The 256 values represented by an 8-bit byte can be interpreted as the values 0 to 255 or as the values −127 to 127.

No, not −128 to 127 as one might expect: the C++ standard leaves open the possibility of one’s-complement hardware and that eliminates one value; thus, a use of −128 is nonportable. Unfortunately, the choice of signed or unsigned for a plain char is implementationdefined. C++ provides two types for which the answer is definite: signed char, which can hold atleast the values −127 to 127, and unsigned char, which can hold at least the values 0 to 255.142Types and DeclarationsChapter 6Fortunately, the difference matters only for values outside the 0 to 127 range, and the most commoncharacters are within that range.Values outside that range stored in a plain char can lead to subtle portability problems. See§6.2.3.1 if you need to use more than one type of char or if you store integers in char variables.Note that the character types are integral types (§6.2.1) so that arithmetic and bitwise logicaloperations (§10.3) apply.

For example:void digits(){for (int i=0; i!=10; ++i)cout << static_cast<char>('0'+i);}This is a way of writing the ten digits to cout. The character literal '0' is converted to its integervalue and i is added. The resulting int is then converted to a char and written to cout. Plain '0'+i isan int, so if I had left out the static_cast<char>, the output would have been something like 48, 49,and so on, rather than 0, 1, and so on.6.2.3.1 Signed and Unsigned CharactersIt is implementation-defined whether a plain char is considered signed or unsigned.

This opens thepossibility for some nasty surprises and implementation dependencies. For example:char c = 255;int i = c;// 255 is ‘‘all ones,’’ hexadecimal 0xFFWhat will be the value of i? Unfortunately, the answer is undefined. On an implementation with8-bit bytes, the answer depends on the meaning of the ‘‘all ones’’ char bit pattern when extendedinto an int. On a machine where a char is unsigned, the answer is 255. On a machine where a charis signed, the answer is −1.

In this case, the compiler might warn about the conversion of the literal255 to the char value −1. However, C++ does not offer a general mechanism for detecting this kindof problem. One solution is to avoid plain char and use the specific char types only. Unfortunately,some standard-library functions, such as strcmp(), take plain chars only (§43.4).A char must behave identically to either a signed char or an unsigned char. However, the threechar types are distinct, so you can’t mix pointers to different char types. For example:void f(char c, signed char sc, unsigned char uc){char∗ pc = &uc;// error : no pointer conversionsigned char∗ psc = pc;// error : no pointer conversionunsigned char∗ puc = pc;// error : no pointer conversionpsc = puc;// error : no pointer conversion}Variables of the three char types can be freely assigned to each other.

However, assigning a toolarge value to a signed char (§10.5.2.1) is still undefined. For example:void g(char c, signed char sc, unsigned char uc){c = 255; // implementation-defined if plain chars are signed and have 8 bitsSection 6.2.3.1c = sc;c = uc;sc = uc;uc = sc;sc = c;uc = c;Signed and Unsigned Characters143// OK// implementation-defined if plain chars are signed and if uc’s value is too large// implementation defined if uc’s value is too large// OK: conversion to unsigned// implementation-defined if plain chars are unsigned and if c’s value is too large// OK: conversion to unsigned}To be concrete, assume that a char is 8 bits:signed char sc = −160;unsigned char uc = sc;cout << uc;// uc == 116 (because 256-160==116)// print 't'char count[256];++count[sc];++count[uc];// assume 8-bit chars// likely disaster: out-of-range access// OKNone of these potential problems and confusions occur if you use plainnegative character values.charthroughout and avoid6.2.3.2 Character LiteralsA character literal is a single character enclosed in single quotes, for example, 'a' and '0'.

The typeof a character literal is char. A character literal can be implicitly converted to its integer value inthe character set of the machine on which the C++ program is to run. For example, if you are running on a machine using the ASCII character set, the value of '0' is 48. The use of character literalsrather than decimal notation makes programs more portable.A few characters have standard names that use the backslash, \ , as an escape character:NameNewlineHorizontal tabVertical tabBackspaceCarriage returnForm feedAlertBackslashQuestion markSingle quoteDouble quoteOctal numberHexadecimal numberASCII NameC++ NameNL (LF)HTVTBSCRFFBEL\n\t\v\b\r\f\a\\\?\’\"\?’"ooohhh\ooo\xhhh...Despite their appearance, these are single characters.We can represent a character from the implementation character set as a one-, two-, or threedigit octal number (\ followed by octal digits) or as a hexadecimal number (\x followed by144Types and DeclarationsChapter 6hexadecimal digits).

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

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

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

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