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

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

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

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

Inthis book, references to the standard are of the form §iso.23.3.6.1. In cases where the text of thisbook is considered imprecise, incomplete, or possibly wrong, consult the standard. But don’texpect the standard to be a tutorial or to be easily accessible by non-experts.Strictly adhering to the C++ language and library standard doesn’t by itself guarantee goodcode or even portable code.

The standard doesn’t say whether a piece of code is good or bad; itsimply says what a programmer can and cannot rely on from an implementation. It is easy to writeperfectly awful standard-conforming programs, and most real-world programs rely on features thatthe standard does not guarantee to be portable. They do so to access system interfaces and136Types and DeclarationsChapter 6hardware features that cannot be expressed directly in C++ or require reliance on specific implementation details.Many important things are deemed implementation-defined by the standard.

This means thateach implementation must provide a specific, well-defined behavior for a construct and that behavior must be documented. For example:unsigned char c1 = 64;unsigned char c2 = 1256;// well defined: a char has at least 8 bits and can always hold 64// implementation-defined: truncation if a char has only 8 bitsThe initialization of c1 is well defined because a char must be at least 8 bits. However, the behaviorof the initialization of c2 is implementation-defined because the number of bits in a char is implementation-defined.

If the char has only 8 bits, the value 1256 will be truncated to 232 (§10.5.2.1).Most implementation-defined features relate to differences in the hardware used to run a program.Other behaviors are unspecified; that is, a range of possible behaviors are acceptable, but theimplementer is not obliged to specify which actually occur. Usually, the reason for deeming something unspecified is that the exact behavior is unpredictable for fundamental reasons.

For example,the exact value returned by new is unspecified. So is the value of a variable assigned to from twothreads unless some synchronization mechanism has been employed to prevent a data race (§41.2).When writing real-world programs, it is usually necessary to rely on implementation-definedbehavior. Such behavior is the price we pay for the ability to operate effectively on a large range ofsystems. For example, C++ would have been much simpler if all characters had been 8 bits and allpointers 32 bits.

However, 16-bit and 32-bit character sets are not uncommon, and machines with16-bit and 64-bit pointers are in wide use.To maximize portability, it is wise to be explicit about what implementation-defined features werely on and to isolate the more subtle examples in clearly marked sections of a program.

A typicalexample of this practice is to present all dependencies on hardware sizes in the form of constantsand type definitions in some header file. To support such techniques, the standard library providesnumeric_limits (§40.2). Many assumptions about implementation-defined features can be checkedby stating them as static assertions (§2.4.3.3). For example:static_assert(4<=sizeof(int),"sizeof(int) too small");Undefined behavior is nastier.

A construct is deemed undefined by the standard if no reasonablebehavior is required by an implementation. Typically, some obvious implementation technique willcause a program using an undefined feature to behave very badly. For example:const int size = 4∗1024;char page[size];void f(){page[size+size] = 7; // undefined}Plausible outcomes of this code fragment include overwriting unrelated data and triggering a hardware error/exception. An implementation is not required to choose among plausible outcomes.Where powerful optimizers are used, the actual effects of undefined behavior can become quiteunpredictable.

If a set of plausible and easily implementable alternatives exist, a feature is deemedSection 6.1The ISO C++ Standard137unspecified or implementation-defined rather than undefined.It is worth spending considerable time and effort to ensure that a program does not use something deemed unspecified or undefined by the standard. In many cases, tools exist to help do this.6.1.1 ImplementationsA C++ implementation can be either hosted or freestanding (§iso.17.6.1.3). A hosted implementation includes all the standard-library facilities as described in the standard (§30.2) and in this book.A freestanding implementation may provide fewer standard-library facilities, as long as the following are provided:Freestanding Implementation HeadersTypesImplementation propertiesInteger typesStart and terminationDynamic memory managementType identificationException handlingInitializer listsOther run-time supportType traitsAtomics<cstddef><cfloat> <limits> <climits><cstdint><cstdlib><new><typeinfo><exception><initializer_list><cstdalign> <cstdarg> <cstdbool><type_traits><atomic>§10.3.1§40.2§43.7§43.7§11.2.3§22.5§30.4.1.1§30.3.1§12.2.4, §44.3.4§35.4.1§41.3Freestanding implementations are meant for code running with only the most minimal operatingsystem support.

Many implementations also provide a (non-standard) option for not using exceptions for really minimal, close-to-the-hardware, programs.6.1.2 The Basic Source Character SetThe C++ standard and the examples in this book are written using the basic source character setconsisting of the letters, digits, graphical characters, and whitespace characters from the U.S. variant of the international 7-bit character set ISO 646-1983 called ASCII (ANSI3.4-1968). This cancause problems for people who use C++ in an environment with a different character set:• ASCII contains punctuation characters and operator symbols (such as ], {, and !) that are notavailable in some character sets.• We need a notation for characters that do not have a convenient character representation(such as newline and ‘‘the character with value 17’’).• ASCII doesn’t contain characters (such as ñ, Þ, and Æ) that are used for writing languagesother than English.To use an extended character set for source code, a programming environment can map theextended character set into the basic source character set in one of several ways, for example, byusing universal character names (§6.2.3.2).138Types and DeclarationsChapter 66.2 TypesConsider:x = y+f(2);For this to make sense in a C++ program, the names x, y, and f must be suitably declared.

That is,the programmer must specify that entities named x, y, and f exist and that they are of types forwhich = (assignment), + (addition), and () (function call), respectively, are meaningful.Every name (identifier) in a C++ program has a type associated with it. This type determineswhat operations can be applied to the name (that is, to the entity referred to by the name) and howsuch operations are interpreted.

For example:float x;int y = 7;float f(int);// x is a floating-point variable// y is an integer variable with the initial value 7// f is a function taking an argument of type int and returning a floating-point numberThese declarations would make the example meaningful. Because y is declared to be an int, it canbe assigned to, used as an operand for +, etc.

On the other hand, f is declared to be a function thattakes an int as its argument, so it can be called given the interger 2.This chapter presents fundamental types (§6.2.1) and declarations (§6.3). Its examples justdemonstrate language features; they are not intended to do anything useful. More extensive andrealistic examples are saved for later chapters. This chapter simply provides the most basic elements from which C++ programs are constructed. You must know these elements, plus the terminology and simple syntax that go with them, in order to complete a real project in C++ and especially to read code written by others.

However, a thorough understanding of every detail mentionedin this chapter is not a requirement for understanding the following chapters. Consequently, youmay prefer to skim through this chapter, observing the major concepts, and return later as the needfor understanding more details arises.6.2.1 Fundamental TypesC++ has a set of fundamental types corresponding to the most common basic storage units of acomputer and the most common ways of using them to hold data:§6.2.2 A Boolean type (bool)§6.2.3 Character types (such as char and wchar_t)§6.2.4 Integer types (such as int and long long)§6.2.5 Floating-point types (such as double and long double)§6.2.7 A type, void, used to signify the absence of informationFrom these types, we can construct other types using declarator operators:§7.2 Pointer types (such as int∗)§7.3 Array types (such as char[])§7.7 Reference types (such as double& and vector<int>&&)In addition, a user can define additional types:§8.2 Data structures and classes (Chapter 16)§8.4 Enumeration types for representing specific sets of values (enum and enum class)Section 6.2.1Fundamental Types139The Boolean, character, and integer types are collectively called integral types.

The integral andfloating-point types are collectively called arithmetic types. Enumerations and classes (Chapter 16)are called user-defined types because they must be defined by users rather than being available foruse without previous declaration, the way fundamental types are. In contrast, fundamental types,pointers, and references are collectively referred to as built-in types. The standard library providesmany user-defined types (Chapter 4, Chapter 5).The integral and floating-point types are provided in a variety of sizes to give the programmer achoice of the amount of storage consumed, the precision, and the range available for computations(§6.2.8).

The assumption is that a computer provides bytes for holding characters, words for holding and computing integer values, some entity most suitable for floating-point computation, andaddresses for referring to those entities. The C++ fundamental types together with pointers andarrays present these machine-level notions to the programmer in a reasonably implementation-independent manner.For most applications, we could use bool for logical values, char for characters, int for integervalues, and double for floating-point values.

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

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

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

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