Главная » Просмотр файлов » Стандарт C++ 98

Стандарт C++ 98 (1119566), страница 32

Файл №1119566 Стандарт C++ 98 (Стандарт C++ 98) 32 страницаСтандарт C++ 98 (1119566) страница 322019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

]4[Note: The requirements on conditions in iteration statements are described in 6.4. —end note]6.5.1 The while statement[stmt.while]1In the while statement the substatement is executed repeatedly until the value of the condition (6.4)becomes false. The test takes place before each execution of the substatement.2When the condition of a while statement is a declaration, the scope of the variable that is declared extendsfrom its point of declaration (3.3.1) to the end of the while statement. A while statement of the formwhile (T t = x) statementis equivalent tolabel:{T t = x;if (t) {statementgoto label;}}// start of condition scope// end of condition scopeThe object created in a condition is destroyed and created with each iteration of the loop.

[Example:struct A {int val;A(int i) : val(i) { }~A() { }operator bool() { return val != 0; }};int i = 1;while (A a = i) {//...i = 0;}In the while-loop, the constructor and destructor are each called twice, once for the condition that succeedsand once for the condition that fails. ]6.5.2 The do statement[stmt.do]1The expression is implicitly converted to bool; if that is not possible, the program is ill-formed.2In the do statement the substatement is executed repeatedly until the value of the expression becomesfalse. The test takes place after each execution of the statement.96© ISO/IECISO/IEC 14882:1998(E)6 Statements6.5.3 The for statement6.5.3 The for statement1[stmt.for]The for statementfor ( for-init-statement conditionopt ; expressionopt ) statementis equivalent to{for-init-statementwhile ( condition ) {statementexpression ;}}except that names declared in the for-init-statement are in the same declarative-region as those declared inthe condition, and except that a continue in statement (not enclosed in another iteration statement) willexecute expression before re-evaluating condition.

[Note: Thus the first statement specifies initializationfor the loop; the condition (6.4) specifies a test, made before each iteration, such that the loop is exitedwhen the condition becomes false; the expression often specifies incrementing that is done after eachiteration. ]2Either or both of the condition and the expression can be omitted. A missing condition makes the impliedwhile clause equivalent to while(true).3If the for-init-statement is a declaration, the scope of the name(s) declared extends to the end of the forstatement. [Example:int i = 42;int a[10];for (int i = 0; i < 10; i++)a[i] = i;int j = i;// j = 42—end example]6.6 Jump statements1[stmt.jump]Jump statements unconditionally transfer control.jump-statement:break ;continue ;return expressionopt ;goto identifier ;2On exit from a scope (however accomplished), destructors (12.4) are called for all constructed objects withautomatic storage duration (3.7.2) (named objects or temporaries) that are declared in that scope, in thereverse order of their declaration.

Transfer out of a loop, out of a block, or back past an initialized variablewith automatic storage duration involves the destruction of variables with automatic storage duration thatare in scope at the point transferred from but not at the point transferred to. (See 6.7 for transfers intoblocks). [Note: However, the program can be terminated (by calling exit() or abort()(18.3), forexample) without destroying class objects with automatic storage duration. ]6.6.1 The break statement1[stmt.break]The break statement shall occur only in an iteration-statement or a switch statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statementfollowing the terminated statement, if any.97ISO/IEC 14882:1998(E)© ISO/IEC6.6.2 The continue statement6 Statements6.6.2 The continue statement1[stmt.cont]The continue statement shall occur only in an iteration-statement and causes control to pass to the loopcontinuation portion of the smallest enclosing iteration-statement, that is, to the end of the loop.

More precisely, in each of the statementswhile (foo) {{// ...}contin: ;}do {{// ...}contin: ;} while (foo);for (;;) {{// ...}contin: ;}a continue not contained in an enclosed iteration statement is equivalent to goto contin.6.6.3 The return statement[stmt.return]1A function returns to its caller by the return statement.2A return statement without an expression can be used only in functions that do not return a value, that is, afunction with the return type void, a constructor (12.1), or a destructor (12.4). A return statement with anexpression of non-void type can be used only in functions returning a value; the value of the expression isreturned to the caller of the function. The expression is implicitly converted to the return type of the function in which it appears.

A return statement can involve the construction and copy of a temporary object(12.2). Flowing off the end of a function is equivalent to a return with no value; this results in undefinedbehavior in a value-returning function.3A return statement with an expression of type “cv void” can be used only in functions with a return typeof cv void; the expression is evaluated just before the function returns to its caller.6.6.4 The goto statement1The goto statement unconditionally transfers control to the statement labeled by the identifier. The identifier shall be a label (6.1) located in the current function.6.7 Declaration statement1[stmt.goto][stmt.dcl]A declaration statement introduces one or more new identifiers into a block; it has the formdeclaration-statement:block-declarationIf an identifier introduced by a declaration was previously declared in an outer block, the outer declarationis hidden for the remainder of the block, after which it resumes its force.2Variables with automatic storage duration (3.7.2) are initialized each time their declaration-statement isexecuted.

Variables with automatic storage duration declared in the block are destroyed on exit from theblock (6.6).3It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps77) from a point where a local variable with automatic storage duration is not in scope to apoint where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without aninitializer (8.5).__________________77) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.98© ISO/IECISO/IEC 14882:1998(E)6 Statements6.7 Declaration statement[Example:void f(){// ...goto lx;// ...ly:X a = 1;// ...lx:goto ly;// ill-formed: jump into scope of a// OK, jump implies destructor// call for a followed by construction// again immediately following label ly}—end example]4The zero-initialization (8.5) of all local objects with static storage duration (3.7.1) is performed before anyother initialization takes place.

A local object of POD type (3.9) with static storage duration initialized withconstant-expressions is initialized before its block is first entered. An implementation is permitted to perform early initialization of other local objects with static storage duration under the same conditions that animplementation is permitted to statically initialize an object with static storage duration in namespace scope(3.6.2). Otherwise such an object is initialized the first time control passes through its declaration; such anobject is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters thedeclaration.

If control re-enters the declaration (recursively) while the object is being initialized, the behavior is undefined. [Example:int foo(int i){static int s = foo(2*i);return i+1;}// recursive call – undefined—end example]5The destructor for a local object with static storage duration will be executed if and only if the variable wasconstructed. [Note: 3.6.3 describes the order in which local objects with static storage duration aredestroyed.

]6.8 Ambiguity resolution1[stmt.ambig]There is an ambiguity in the grammar involving expression-statements and declarations: An expressionstatement with a function-style explicit type conversion (5.2.3) as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a (. In those cases the statement is adeclaration.

[Note: To disambiguate, the whole statement might have to be examined to determine if it isan expression-statement or a declaration. This disambiguates many examples. [Example: assuming T is asimple-type-specifier (7.1.5),T(a)->m = 7;T(a)++;T(a,5)<<c;// expression-statement// expression-statement// expression-statementT(*d)(int);T(e)[5];T(f) = { 1, 2 };T(*g)(double(3));// declaration// declaration// declaration// declarationIn the last example above, g, which is a pointer to T, is initialized to double(3).

This is of course illformed for semantic reasons, but that does not affect the syntactic analysis. —end example]99ISO/IEC 14882:1998(E)© ISO/IEC6.8 Ambiguity resolution26 StatementsThe remaining cases are declarations. [Example:class T {// ...public:T();T(int);T(int, int);};T(a);T(*b)();T(c)=7;T(d),e,f=3;extern int h;T(g)(h,2);// declaration// declaration// declaration// declaration// declaration—end example] —end note]3The disambiguation is purely syntactic; that is, the meaning of the names occurring in such a statement,beyond whether they are type-names or not, is not generally used in or changed by the disambiguation.Class templates are instantiated as necessary to determine if a qualified name is a type-name. Disambiguation precedes parsing, and a statement disambiguated as a declaration may be an ill-formed declaration.

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

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

Список файлов учебной работы

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