Главная » Просмотр файлов » Стандарт языка Си С99 TC

Стандарт языка Си С99 TC (1113411), страница 22

Файл №1113411 Стандарт языка Си С99 TC (Стандарт языка Си С99 + TC) 22 страницаСтандарт языка Си С99 TC (1113411) страница 222019-04-24СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Anassignment expression has the value of the left operand after the assignment, but is not anlvalue. The type of an assignment expression is the type of the left operand unless theleft operand has qualified type, in which case it is the unqualified version of the type ofthe left operand. The side effect of updating the stored value of the left operand shalloccur between the previous and the next sequence point.4The order of evaluation of the operands is unspecified. If an attempt is made to modifythe result of an assignment operator or to access it after the next sequence point, thebehavior is undefined.§6.5.16Language91ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N12566.5.16.1 Simple assignmentConstraints1One of the following shall hold:96)— the left operand has qualified or unqualified arithmetic type and the right hasarithmetic type;— the left operand has a qualified or unqualified version of a structure or union typecompatible with the type of the right;— both operands are pointers to qualified or unqualified versions of compatible types,and the type pointed to by the left has all the qualifiers of the type pointed to by theright;— one operand is a pointer to an object or incomplete type and the other is a pointer to aqualified or unqualified version of void, and the type pointed to by the left has allthe qualifiers of the type pointed to by the right;— the left operand is a pointer and the right is a null pointer constant; or— the left operand has type _Bool and the right is a pointer.Semantics2In simple assignment (=), the value of the right operand is converted to the type of theassignment expression and replaces the value stored in the object designated by the leftoperand.3If the value being stored in an object is read from another object that overlaps in any waythe storage of the first object, then the overlap shall be exact and the two objects shallhave qualified or unqualified versions of a compatible type; otherwise, the behavior isundefined.4EXAMPLE 1In the program fragmentint f(void);char c;/* ...

*/if ((c = f()) == -1)/* ... */the int value returned by the function may be truncated when stored in the char, and then converted backto int width prior to the comparison. In an implementation in which ‘‘plain’’ char has the same range ofvalues as unsigned char (and char is narrower than int), the result of the conversion cannot be96) The asymmetric appearance of these constraints with respect to type qualifiers is due to the conversion(specified in 6.3.2.1) that changes lvalues to ‘‘the value of the expression’’ and thus removes any typequalifiers that were applied to the type category of the expression (for example, it removes const butnot volatile from the type int volatile * const).92Language§6.5.16.1WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC3negative, so the operands of the comparison can never compare equal.

Therefore, for full portability, thevariable c should be declared as int.5EXAMPLE 2In the fragment:char c;int i;long l;l = (c = i);the value of i is converted to the type of the assignment expression c = i, that is, char type. The valueof the expression enclosed in parentheses is then converted to the type of the outer assignment expression,that is, long int type.6EXAMPLE 3Consider the fragment:const char **cpp;char *p;const char c = 'A';cpp = &p;*cpp = &c;*p = 0;// constraint violation// valid// validThe first assignment is unsafe because it would allow the following valid code to attempt to change thevalue of the const object c.6.5.16.2 Compound assignmentConstraints1For the operators += and -= only, either the left operand shall be a pointer to an objecttype and the right shall have integer type, or the left operand shall have qualified orunqualified arithmetic type and the right shall have arithmetic type.2For the other operators, each operand shall have arithmetic type consistent with thoseallowed by the corresponding binary operator.Semantics3A compound assignment of the form E1 op = E2 differs from the simple assignmentexpression E1 = E1 op (E2) only in that the lvalue E1 is evaluated only once.§6.5.16.2Language93ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N12566.5.17 Comma operatorSyntax1expression:assignment-expressionexpression , assignment-expressionSemantics2The left operand of a comma operator is evaluated as a void expression; there is asequence point after its evaluation.

Then the right operand is evaluated; the result has itstype and value.97) If an attempt is made to modify the result of a comma operator or toaccess it after the next sequence point, the behavior is undefined.3EXAMPLE As indicated by the syntax, the comma operator (as described in this subclause) cannotappear in contexts where a comma is used to separate items in a list (such as arguments to functions or listsof initializers).

On the other hand, it can be used within a parenthesized expression or within the secondexpression of a conditional operator in such contexts. In the function callf(a, (t=3, t+2), c)the function has three arguments, the second of which has the value 5.Forward references: initialization (6.7.8).97) A comma operator does not yield an lvalue.94Language§6.5.17WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC36.6 Constant expressionsSyntax1constant-expression:conditional-expressionDescription2A constant expression can be evaluated during translation rather than runtime, andaccordingly may be used in any place that a constant may be.Constraints3Constant expressions shall not contain assignment, increment, decrement, function-call,or comma operators, except when they are contained within a subexpression that is notevaluated.98)4Each constant expression shall evaluate to a constant that is in the range of representablevalues for its type.Semantics5An expression that evaluates to a constant is required in several contexts.

If a floatingexpression is evaluated in the translation environment, the arithmetic precision and rangeshall be at least as great as if the expression were being evaluated in the executionenvironment.6An integer constant expression99) shall have integer type and shall only have operandsthat are integer constants, enumeration constants, character constants, sizeofexpressions whose results are integer constants, and floating constants that are theimmediate operands of casts. Cast operators in an integer constant expression shall onlyconvert arithmetic types to integer types, except as part of an operand to the sizeofoperator.7More latitude is permitted for constant expressions in initializers.

Such a constantexpression shall be, or evaluate to, one of the following:— an arithmetic constant expression,— a null pointer constant,98) The operand of a sizeof operator is usually not evaluated (6.5.3.4).99) An integer constant expression is used to specify the size of a bit-field member of a structure, thevalue of an enumeration constant, the size of an array, or the value of a case constant. Furtherconstraints that apply to the integer constant expressions used in conditional-inclusion preprocessingdirectives are discussed in 6.10.1.§6.6Language95ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N1256— an address constant, or— an address constant for an object type plus or minus an integer constant expression.8An arithmetic constant expression shall have arithmetic type and shall only haveoperands that are integer constants, floating constants, enumeration constants, characterconstants, and sizeof expressions.

Cast operators in an arithmetic constant expressionshall only convert arithmetic types to arithmetic types, except as part of an operand to asizeof operator whose result is an integer constant.9An address constant is a null pointer, a pointer to an lvalue designating an object of staticstorage duration, or a pointer to a function designator; it shall be created explicitly usingthe unary & operator or an integer constant cast to pointer type, or implicitly by the use ofan expression of array or function type. The array-subscript [] and member-access .and -> operators, the address & and indirection * unary operators, and pointer casts maybe used in the creation of an address constant, but the value of an object shall not beaccessed by use of these operators.10An implementation may accept other forms of constant expressions.11The semantic rules for the evaluation of a constant expression are the same as fornonconstant expressions.100)Forward references: array declarators (6.7.5.2), initialization (6.7.8).100) Thus, in the following initialization,static int i = 2 || 1 / 0;the expression is a valid integer constant expression with value one.96Language§6.6WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC36.7 DeclarationsSyntax1declaration:declaration-specifiers init-declarator-listopt ;declaration-specifiers:storage-class-specifier declaration-specifiersopttype-specifier declaration-specifiersopttype-qualifier declaration-specifiersoptfunction-specifier declaration-specifiersoptinit-declarator-list:init-declaratorinit-declarator-list , init-declaratorinit-declarator:declaratordeclarator = initializerConstraints2A declaration shall declare at least a declarator (other than the parameters of a function orthe members of a structure or union), a tag, or the members of an enumeration.3If an identifier has no linkage, there shall be no more than one declaration of the identifier(in a declarator or type specifier) with the same scope and in the same name space, exceptfor tags as specified in 6.7.2.3.4All declarations in the same scope that refer to the same object or function shall specifycompatible types.Semantics5A declaration specifies the interpretation and attributes of a set of identifiers.

A definitionof an identifier is a declaration for that identifier that:— for an object, causes storage to be reserved for that object;— for a function, includes the function body;101)— for an enumeration constant or typedef name, is the (only) declaration of theidentifier.6The declaration specifiers consist of a sequence of specifiers that indicate the linkage,storage duration, and part of the type of the entities that the declarators denote. The initdeclarator-list is a comma-separated sequence of declarators, each of which may have101) Function definitions have a different syntax, described in 6.9.1.§6.7Language97ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N1256additional type information, or an initializer, or both. The declarators contain theidentifiers (if any) being declared.7If an identifier for an object is declared with no linkage, the type for the object shall becomplete by the end of its declarator, or by the end of its init-declarator if it has aninitializer; in the case of function parameters (including in prototypes), it is the adjustedtype (see 6.7.5.3) that is required to be complete.Forward references: declarators (6.7.5), enumeration specifiers (6.7.2.2), initialization(6.7.8).6.7.1 Storage-class specifiersSyntax1storage-class-specifier:typedefexternstaticautoregisterConstraints2At most, one storage-class specifier may be given in the declaration specifiers in adeclaration.102)Semantics3The typedef specifier is called a ‘‘storage-class specifier’’ for syntactic convenienceonly; it is discussed in 6.7.7.

The meanings of the various linkages and storage durationswere discussed in 6.2.2 and 6.2.4.4A declaration of an identifier for an object with storage-class specifier registersuggests that access to the object be as fast as possible. The extent to which suchsuggestions are effective is implementation-defined.103)5The declaration of an identifier for a function that has block scope shall have no explicitstorage-class specifier other than extern.102) See ‘‘future language directions’’ (6.11.5).103) The implementation may treat any register declaration simply as an auto declaration. However,whether or not addressable storage is actually used, the address of any part of an object declared withstorage-class specifier register cannot be computed, either explicitly (by use of the unary &operator as discussed in 6.5.3.2) or implicitly (by converting an array name to a pointer as discussed in6.3.2.1).

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

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

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

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