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

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

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

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

The loop variable, the termination condition, and the expression that updates the loop variable are explicitly presented ‘‘up front’’ on a single line. For example:void f(int v[], int max){for (int i = 0; i!=max; ++i)v[i] = i∗i;}This is equivalent tovoid f(int v[], int max){int i = 0;// introduce loop variablewhile (i!=max) {// test termination conditionv[i] = i∗i; // execute the loop body++i;// increment loop variable}}A variable can be declared in the initializer part of a for-statement. If that initializer is a declaration, the variable (or variables) it introduced is in scope until the end of the for-statement.It is not always obvious what is the right type to use for a controlled variable in a for loop, soauto often comes in handy:for (auto p = begin(c); c!=end(c); ++p) {// ...

use iterator p for elements in container c ...}If the final value of an index needs to be known after exit from a for-loop, the index variable mustbe declared outside the for-loop (e.g., see §9.6).If no initialization is needed, the initializing statement can be empty.If the expression that is supposed to increment the loop variable is omitted, we must updatesome form of loop variable elsewhere, typically in the body of the loop.

If the loop isn’t of the simple ‘‘introduce a loop variable, test the condition, update the loop variable’’ variety, it is often betterexpressed as a while-statement. However, consider this elegant variant:for (string s; cin>>s;)v.push_back(s);Here, the reading and testing for termination and combined in cin>>s, so we don’t need an explicitloop variable. On the other hand, the use of for, rather than while, allows us to limit the scope of the‘‘current element,’’ s, to the loop itself (the for-statement).A for-statement is also useful for expressing a loop without an explicit termination condition:for (;;) { // ‘‘forever’’// ...}236StatementsChapter 9However, many consider this idiom obscure and prefer to use:while(true) {// ...}// ‘‘forever’’9.5.3 while StatementsA while-statement executes its controlled statement until its condition becomes false. For example:template<class Iter, class Value>Iter find(Iter first, Iter last, Value val){while (first!=last && ∗first!=val)++first;return first;}I tend to prefer while-statements over for-statements when there isn’t an obvious loop variable orwhere the update of a loop variable naturally comes in the middle of the loop body.A for-statement (§9.5.2) is easily rewritten into an equivalent while-statement and vice versa.9.5.4 do StatementsA do-statement is similar to aexample:while-statementvoid print_backwards(char a[], int i){cout << '{';do {cout << a[−−i];} while (i);cout << '}';}except that the condition comes after the body.

For// i must be positiveThis might be called like this: print_backwards(s,strlen(s)); but it is all too easy to make a horriblemistake. For example, what if s was the empty string?In my experience, the do-statement is a source of errors and confusion. The reason is that itsbody is always executed once before the condition is evaluated.

However, for the body to work correctly, something very much like the condition must hold even the first time through. More oftenthan I would have guessed, I have found that condition not to hold as expected either when the program was first written and tested or later after the code preceding it has been modified. I also preferthe condition ‘‘up front where I can see it.’’ Consequently, I recommend avoiding do-statements.9.5.5 Loop ExitIf the condition of an iteration statement (a for-, while-, or do-statement) is omitted, the loop willnot terminate unless the user explicitly exits it by a break, return (§12.1.4), goto (§9.6), throw(§13.5), or some less obvious way such as a call of exit() (§15.4.3).

A break ‘‘breaks out of’’ theSection 9.5.5Loop Exit237nearest enclosing switch-statement (§9.4.2) or iteration-statement. For example:void f(vector<string>& v, string terminator){char c;string s;while (cin>>c) {// ...if (c == '\n') break;// ...}}We use a break when we need to leave the loop body ‘‘in the middle.’’ Unless it warps the logic ofa loop (e.g., requires the introduction of an extra varible), it is usually better to have the completeexit condition as the condition of a while-statement or a for-statement.Sometimes, we don’t want to exit the loop completely, we just want to get to the end of the loopbody. A continue skips the rest of the body of an iteration-statement.

For example:void find_prime(vector<string>& v){for (int i = 0; i!=v.size(); ++i) {if (!prime(v[i]) continue;return v[i];}}After a continue, the increment part of the loop (if any) is executed, followed by the loop condition(if any). So find_prime() could equivalently have been written as:void find_prime(vector<string>& v){for (int i = 0; i!=v.size(); ++i) {if (!prime(v[i]) {return v[i];}}}9.6 goto StatementsC++ possesses the infamous goto:identifier ;identifier : statementgotoThe goto has few uses in general high-level programming, but it can be very useful when C++ codeis generated by a program rather than written directly by a person; for example, gotos can be usedin a parser generated from a grammar by a parser generator.238StatementsChapter 9The scope of a label is the function it is in (§6.3.4).

This implies that you can use goto to jumpboth into and out of blocks. The only restriction is that you cannot jump past an initializer or intoan exception handler (§13.5).One of the few sensible uses of goto in ordinary code is to break out from a nested loop orswitch-statement (a break breaks out of only the innermost enclosing loop or switch-statement). Forexample:void do_something(int i, int j)// do something to a two-dimensional matrix called mn{for (i = 0; i!=n; ++i)for (j = 0; j!=m; ++j)if (nm[i][j] == a)goto found;// not found// ...found:// nm[i][j] == a}Note that this goto just jumps forward to exit its loop. It does not introduce a new loop or enter anew scope.

That makes it the least troublesome and least confusing use of a goto.9.7 Comments and IndentationJudicious use of comments and consistent use of indentation can make the task of reading andunderstanding a program much more pleasant. Several different consistent styles of indentation arein use. I see no fundamental reason to prefer one over another (although, like most programmers, Ihave my preferences, and this book reflects them). The same applies to styles of comments.Comments can be misused in ways that seriously affect the readability of a program.

The compiler does not understand the contents of a comment, so it has no way of ensuring that a comment• is meaningful,• describes the program, and• is up to date.Most programs contain comments that are incomprehensible, ambiguous, and just plain wrong.Bad comments can be worse than no comments.If something can be stated in the language itself, it should be, and not just mentioned in a comment. This remark is aimed at comments such as these:// variable "v" must be initialized// variable "v" must be used only by function "f()"// call function "init()" before calling any other function in this file// call function "cleanup()" at the end of your programSection 9.7Comments and Indentation239// don’t use function "weird()"// function "f(int ...)" takes two or three argumentsSuch comments can typically be rendered unnecessary by proper use of C++.Once something has been stated clearly in the language, it should not be mentioned a secondtime in a comment.

For example:a = b+c; // a becomes b+ccount++; // increment the counterSuch comments are worse than simply redundant. They increase the amount of text the reader hasto look at, they often obscure the structure of the program, and they may be wrong. Note, however,that such comments are used extensively for teaching purposes in programming language textbookssuch as this. This is one of the many ways a program in a textbook differs from a real program.A good comment states what a piece of code is supposed to do (the intent of the code), whereasthe code (only) states what it does (in terms of how it does it).

Preferably, a comment is expressedat a suitably high level of abstraction so that it is easy for a human to understand without delvinginto minute details.My preference is for:• A comment for each source file stating what the declarations in it have in common, references to manuals, the name of the programmer, general hints for maintenance, etc.• A comment for each class, template, and namespace• A comment for each nontrivial function stating its purpose, the algorithm used (unless it isobvious), and maybe something about the assumptions it makes about its environment• A comment for each global and namespace variable and constant• A few comments where the code is nonobvious and/or nonportable• Very little elseFor example://tbl.c: Implementation of the symbol table./*Gaussian elimination with partial pivoting.See Ralston: "A first course ..." pg 411.*///scan(p,n,c) requires that p points to an array of at least n elements// sor t(p,q) sorts the elements of the sequence [p:q) using < for comparison.// Revised to handle invalid dates.

Bjarne Stroustrup, Feb 29 2013A well-chosen and well-written set of comments is an essential part of a good program. Writinggood comments can be as difficult as writing the program itself. It is an art well worth cultivating.240StatementsChapter 9Note that /∗ ∗/ style comments do not nest. For example:/*remove expensive checkif (check(p,q)) error("bad p q") /* should never happen */∗/This nesting should give an error for an unmatched final ∗/.9.8 Advice[1][2][3][4][5][6][7][8][9][10][11]Don’t declare a variable until you have a value to initialize it with; §9.3, §9.4.3, §9.5.2.Prefer a switch-statement to an if-statement when there is a choice; §9.4.2.Prefer a range-for-statement to a for-statement when there is a choice; §9.5.1.Prefer a for-statement to a while-statement when there is an obvious loop variable; §9.5.2.Prefer a while-statement to a for-statement when there is no obvious loop variable; §9.5.3.Avoid do-statements; §9.5.Avoid goto; §9.6.Keep comments crisp; §9.7.Don’t say in comments what can be clearly stated in code; §9.7.State intent in comments; §9.7.Maintain a consistent indentation style; §9.7.10ExpressionsProgramming is like sex:It may give some concrete results,but that is not why we do it.– apologies to Richard Feynman••••••IntroductionA Desk CalculatorThe Parser; Input; Low-Level Input; Error Handling; The Driver; Headers; Command-LineArguments; A Note on StyleOperator SummaryResults; Order of Evaluation; Operator Precedence; Temporary ObjectsConstant ExpressionsSymbolic Constants; consts in Constant Expressions; Literal Types; Reference Arguments;Address Constant ExpressionsImplicit Type ConversionPromotions; Conversions; Usual Arithmetic ConversionsAdvice10.1 IntroductionThis chapter discusses expressions in some detail.

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

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

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

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