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

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

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

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

Consequently, l0, lO, l1, ll, and I1l are poor choices for identifier names. Not all fonts have the same problems, but most have some.Names from a large scope ought to have relatively long and reasonably obvious names, such asvector, Window_with_border, and Department_number. However, code is clearer if names used onlyin a small scope have short, conventional names such as x, i, and p.

Functions (Chapter 12), classes(Chapter 16), and namespaces (§14.3.1) can be used to keep scopes small. It is often useful to keepfrequently used names relatively short and reserve really long names for infrequently used entities.156Types and DeclarationsChapter 6Choose names to reflect the meaning of an entity rather than its implementation.

For example,is better than number_vector even if the phone numbers happen to be stored in a vector(§4.4). Do not encode type information in a name (e.g., pcname for a name that’s a char∗ or icountfor a count that’s an int) as is sometimes done in languages with dynamic or weak type systems:• Encoding types in names lowers the abstraction level of the program; in particular, it prevents generic programming (which relies on a name being able to refer to entities of different types).• The compiler is better at keeping track of types than you are.• If you want to change the type of a name (e.g., use a std::string to hold the name), you’llhave to change every use of the name (or the type encoding becomes a lie).• Any system of type abbreviations you can come up with will become overelaborate andcryptic as the variety of types you use increases.Choosing good names is an art.Try to maintain a consistent naming style.

For example, capitalize names of user-defined typesand start names of non-type entities with a lowercase letter (for example, Shape and current_token).Also, use all capitals for macros (if you must use macros (§12.6); for example, HACK) and never fornon-macros (not even for non-macro constants). Use underscores to separate words in an identifier;number_of_elements is more readable than numberOfElements. However, consistency is hard toachieve because programs are typically composed of fragments from different sources and severaldifferent reasonable styles are in use.

Be consistent in your use of abbreviations and acronyms.Note that the language and the standard library use lowercase for types; this can be seen as a hintthat they are part of the standard.phone_book6.3.3.1 KeywordsThe C++ keywords are:C++ Keywordsalignasbitandcharconstexprdoexternifneworreinterpret_caststatic_assertthread_localtypenamevolatilealignofbitorchar16_tconst_castdoublefalseinlinenoexceptor_eqreturnstatic_castthrowunionwchar_tandboolchar32_tcontinuedynamic_castfloatintnotprivateshortstructtrueunsignedwhileIn addition, the word export is reserved for future use.and_eqbreakclassdecltypeelseforlongnot_eqprotectedsignedswitchtryusingxorasmcasecompldefaultenumfriendmutablenullptrpublicsizeoftemplatetypedefvirtualxor_eqautocatchconstdeleteexplicitgotonamespaceoperatorregisterstaticthistypeidvoidSection 6.3.4Scope1576.3.4 ScopeA declaration introduces a name into a scope; that is, a name can be used only in a specific part ofthe program text.• Local scope: A name declared in a function (Chapter 12) or lambda (§11.4) is called a localname.

Its scope extends from its point of declaration to the end of the block in which its declaration occurs. A block is a section of code delimited by a {} pair. Function and lambdaparameter names are considered local names in the outermost block of their function orlambda.• Class scope: A name is called a member name (or a class member name) if it is defined in aclass outside any function, class (Chapter 16), enum class (§8.4.1), or other namespace. Itsscope extends from the opening { of the class declaration to the end of the class declaration.• Namespace scope: A name is called a namespace member name if it is defined in a namespace (§14.3.1) outside any function, lambda (§11.4), class (Chapter 16), enum class(§8.4.1), or other namespace.

Its scope extends from the point of declaration to the end ofits namespace. A namespace name may also be accessible from other translation units(§15.2).• Global scope: A name is called a global name if it is defined outside any function, class(Chapter 16), enum class (§8.4.1), or namespace (§14.3.1). The scope of a global nameextends from the point of declaration to the end of the file in which its declaration occurs.

Aglobal name may also be accessible from other translation units (§15.2). Technically, theglobal namespace is considered a namespace, so a global name is an example of a namespace member name.• Statement scope: A name is in a statement scope if it is defined within the () part of a for-,while-, if-, or switch-statement. Its scope extends from its point of declaration to the end ofits statement. All names in statement scope are local names.• Function scope: A label (§9.6) is in scope from its point of declaration until the end of thefunction.A declaration of a name in a block can hide a declaration in an enclosing block or a global name.That is, a name can be redefined to refer to a different entity within a block. After exit from theblock, the name resumes its previous meaning.

For example:int x;void f(){int x;x = 1;{int x;x = 2;}x = 3;}int∗ p = &x;// global x// local x hides global x// assign to local x// hides first local x// assign to second local x// assign to first local x// take address of global x158Types and DeclarationsChapter 6Hiding names is unavoidable when writing large programs. However, a human reader can easilyfail to notice that a name has been hidden (also known as shadowed).

Because such errors are relatively rare, they can be very difficult to find. Consequently, name hiding should be minimized.Using names such as i and x for global variables or for local variables in a large function is askingfor trouble.A hidden global name can be referred to using the scope resolution operator, ::. For example:int x;void f2(){int x = 1; // hide global x::x = 2;// assign to global xx = 2;// assign to local x// ...}There is no way to use a hidden local name.The scope of a name that is not a class member starts at its point of declaration, that is, after thecomplete declarator and before the initializer. This implies that a name can be used even to specifyits own initial value. For example:int x = 97;void f3(){int x = x;}// perverse: initialize x with its own (uninitialized) valueA good compiler warns if a variable is used before it has been initialized.It is possible to use a single name to refer to two different objects in a block without using the ::operator.

For example:int x = 11;void f4(){int y = x;int x = 22;y = x;}// perverse: use of two different objects both called x in a single scope// use global x: y = 11// use local x: y = 22Again, such subtleties are best avoided.The names of function arguments are considered declared in the outermost block of a function.For example:void f5(int x){int x;}// errorSection 6.3.4Scope159This is an error because x is defined twice in the same scope.Names introduced in a for-statement are local to that statement (in statement scope).

Thisallows us to use conventional names for loop variables repeatedly in a function. For example:void f(vector<string>& v, list<int>& lst){for (const auto& x : v) cout << x << '\n';for (auto x : lst) cout << x << '\n';for (int i = 0, i!=v.size(), ++i) cout << v[i] << '\n';for (auto i : {1, 2, 3, 4, 5, 6, 7}) cout << i << '\n';}This contains no name clashes.A declaration is not allowed as the only statement on the branch of an if-statement (§9.4.1).6.3.5 InitializationIf an initializer is specified for an object, that initializer determines the initial value of an object.An initializer can use one of four syntactic styles:X a1 {v};X a2 = {v};X a3 = v;X a4(v);Of these, only the first can be used in every context, and I strongly recommend its use. It is clearerand less error-prone than the alternatives.

However, the first form (used for a1) is new in C++11, sothe other three forms are what you find in older code. The two forms using = are what you use inC. Old habits die hard, so I sometimes (inconsistently) use = when initializing a simple variablewith a simple value. For example:int x1 = 0;char c1 = 'z';However, anything much more complicated than that is better done using {}. Initialization using {},list initialization, does not allow narrowing (§iso.8.5.4). That is:• An integer cannot be converted to another integer that cannot hold its value. For example,char to int is allowed, but not int to char.• A floating-point value cannot be converted to another floating-point type that cannot hold itsvalue.

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

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

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

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