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

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

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

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

The assignment to t1.d[0] is probably undefined behavior, but it is possible thatsizeof (struct s) >= offsetof(struct s, d) + sizeof (double)in which case the assignment would be legitimate. Nevertheless, it cannot appear in strictly conformingcode.19After the further declaration:struct ss { int n; };the expressions:sizeof (struct s) >= sizeof (struct ss)sizeof (struct s) >= offsetof(struct s, d)are always equal to 1.20If sizeof (double) is 8, then after the following code is executed:struct s *s1;struct s *s2;s1 = malloc(sizeof (struct s) + 64);s2 = malloc(sizeof (struct s) + 46);and assuming that the calls to malloc succeed, the objects pointed to by s1 and s2 behave, for mostpurposes, as if the identifiers had been declared as:struct { int n; double d[8]; } *s1;struct { int n; double d[5]; } *s2;21Following the further successful assignments:s1 = malloc(sizeof (struct s) + 10);s2 = malloc(sizeof (struct s) + 6);they then behave as if the declarations were:struct { int n; double d[1]; } *s1, *s2;and:double *dp;dp = &(s1->d[0]);*dp = 42;dp = &(s2->d[0]);*dp = 42;22////////validvalidvalidundefined behaviorThe assignment:*s1 = *s2;only copies the member n; if any of the array elements are within the first sizeof (struct s) bytesof the structure, they might be copied or simply overwritten with indeterminate values.Forward references: tags (6.7.2.3).104Language§6.7.2.1WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC36.7.2.2 Enumeration specifiersSyntax1enum-specifier:enum identifieropt { enumerator-list }enum identifieropt { enumerator-list , }enum identifierenumerator-list:enumeratorenumerator-list , enumeratorenumerator:enumeration-constantenumeration-constant = constant-expressionConstraints2The expression that defines the value of an enumeration constant shall be an integerconstant expression that has a value representable as an int.Semantics3The identifiers in an enumerator list are declared as constants that have type int andmay appear wherever such are permitted.109) An enumerator with = defines itsenumeration constant as the value of the constant expression.

If the first enumerator hasno =, the value of its enumeration constant is 0. Each subsequent enumerator with no =defines its enumeration constant as the value of the constant expression obtained byadding 1 to the value of the previous enumeration constant. (The use of enumerators with= may produce enumeration constants with values that duplicate other values in the sameenumeration.) The enumerators of an enumeration are also known as its members.4Each enumerated type shall be compatible with char, a signed integer type, or anunsigned integer type.

The choice of type is implementation-defined,110) but shall becapable of representing the values of all the members of the enumeration. Theenumerated type is incomplete until after the } that terminates the list of enumeratordeclarations.109) Thus, the identifiers of enumeration constants declared in the same scope shall all be distinct fromeach other and from other identifiers declared in ordinary declarators.110) An implementation may delay the choice of which integer type until all enumeration constants havebeen seen.§6.7.2.2Language105ISO/IEC 9899:TC35EXAMPLECommittee Draft — Septermber 7, 2007WG14/N1256The following fragment:enum hue { chartreuse, burgundy, claret=20, winedark };enum hue col, *cp;col = claret;cp = &col;if (*cp != burgundy)/* ...

*/makes hue the tag of an enumeration, and then declares col as an object that has that type and cp as apointer to an object that has that type. The enumerated values are in the set { 0, 1, 20, 21 }.Forward references: tags (6.7.2.3).6.7.2.3 TagsConstraints1A specific type shall have its content defined at most once.2Where two declarations that use the same tag declare the same type, they shall both usethe same choice of struct, union, or enum.3A type specifier of the formenum identifierwithout an enumerator list shall only appear after the type it specifies is complete.Semantics4All declarations of structure, union, or enumerated types that have the same scope anduse the same tag declare the same type.

The type is incomplete111) until the closing braceof the list defining the content, and complete thereafter.5Two declarations of structure, union, or enumerated types which are in different scopes oruse different tags declare distinct types. Each declaration of a structure, union, orenumerated type which does not include a tag declares a distinct type.6A type specifier of the formstruct-or-union identifieropt { struct-declaration-list }orenum identifier { enumerator-list }orenum identifier { enumerator-list , }declares a structure, union, or enumerated type. The list defines the structure content,111) An incomplete type may only by used when the size of an object of that type is not needed.

It is notneeded, for example, when a typedef name is declared to be a specifier for a structure or union, orwhen a pointer to or a function returning a structure or union is being declared. (See incomplete typesin 6.2.5.) The specification has to be complete before such a function is called or defined.106Language§6.7.2.3WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC3union content, or enumeration content. If an identifier is provided,112) the type specifieralso declares the identifier to be the tag of that type.7A declaration of the formstruct-or-union identifier ;specifies a structure or union type and declares the identifier as a tag of that type.113)8If a type specifier of the formstruct-or-union identifieroccurs other than as part of one of the above forms, and no other declaration of theidentifier as a tag is visible, then it declares an incomplete structure or union type, anddeclares the identifier as the tag of that type.113)9If a type specifier of the formstruct-or-union identifierorenum identifieroccurs other than as part of one of the above forms, and a declaration of the identifier as atag is visible, then it specifies the same type as that other declaration, and does notredeclare the tag.10EXAMPLE 1This mechanism allows declaration of a self-referential structure.struct tnode {int count;struct tnode *left, *right;};specifies a structure that contains an integer and two pointers to objects of the same type.

Once thisdeclaration has been given, the declarationstruct tnode s, *sp;declares s to be an object of the given type and sp to be a pointer to an object of the given type. Withthese declarations, the expression sp->left refers to the left struct tnode pointer of the object towhich sp points; the expression s.right->count designates the count member of the right structtnode pointed to from s.11The following alternative formulation uses the typedef mechanism:112) If there is no identifier, the type can, within the translation unit, only be referred to by the declarationof which it is a part.

Of course, when the declaration is of a typedef name, subsequent declarationscan make use of that typedef name to declare objects having the specified structure, union, orenumerated type.113) A similar construction with enum does not exist.§6.7.2.3Language107ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N1256typedef struct tnode TNODE;struct tnode {int count;TNODE *left, *right;};TNODE s, *sp;12EXAMPLE 2 To illustrate the use of prior declaration of a tag to specify a pair of mutually referentialstructures, the declarationsstruct s1 { struct s2 *s2p; /* ... */ }; // D1struct s2 { struct s1 *s1p; /* ... */ }; // D2specify a pair of structures that contain pointers to each other.

Note, however, that if s2 were alreadydeclared as a tag in an enclosing scope, the declaration D1 would refer to it, not to the tag s2 declared inD2. To eliminate this context sensitivity, the declarationstruct s2;may be inserted ahead of D1. This declares a new tag s2 in the inner scope; the declaration D2 thencompletes the specification of the new type.Forward references: declarators (6.7.5), array declarators (6.7.5.2), type definitions(6.7.7).6.7.3 Type qualifiersSyntax1type-qualifier:constrestrictvolatileConstraints2Types other than pointer types derived from object or incomplete types shall not berestrict-qualified.Semantics3The properties associated with qualified types are meaningful only for expressions thatare lvalues.114)4If the same qualifier appears more than once in the same specifier-qualifier-list, eitherdirectly or via one or more typedefs, the behavior is the same as if it appeared onlyonce.114) The implementation may place a const object that is not volatile in a read-only region ofstorage.

Moreover, the implementation need not allocate storage for such an object if its address isnever used.108Language§6.7.3WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC35If an attempt is made to modify an object defined with a const-qualified type through useof an lvalue with non-const-qualified type, the behavior is undefined.

If an attempt ismade to refer to an object defined with a volatile-qualified type through use of an lvaluewith non-volatile-qualified type, the behavior is undefined.115)6An object that has volatile-qualified type may be modified in ways unknown to theimplementation or have other unknown side effects. Therefore any expression referringto such an object shall be evaluated strictly according to the rules of the abstract machine,as described in 5.1.2.3. Furthermore, at every sequence point the value last stored in theobject shall agree with that prescribed by the abstract machine, except as modified by theunknown factors mentioned previously.116) What constitutes an access to an object thathas volatile-qualified type is implementation-defined.7An object that is accessed through a restrict-qualified pointer has a special associationwith that pointer.

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

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

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

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