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

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

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

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

Likewise, an identifier currentlydefined as a function-like macro shall not be redefined by another #definepreprocessing directive unless the second definition is a function-like macro definitionthat has the same number and spelling of parameters, and the two replacement lists areidentical.3There shall be white-space between the identifier and the replacement list in the definitionof an object-like macro.4If the identifier-list in the macro definition does not end with an ellipsis, the number ofarguments (including those arguments consisting of no preprocessing tokens) in aninvocation of a function-like macro shall equal the number of parameters in the macrodefinition. Otherwise, there shall be more arguments in the invocation than there areparameters in the macro definition (excluding the ...).

There shall exist a )preprocessing token that terminates the invocation.5The identifier _ _VA_ARGS_ _ shall occur only in the replacement-list of a function-likemacro that uses the ellipsis notation in the parameters.6A parameter identifier in a function-like macro shall be uniquely declared within itsscope.Semantics7The identifier immediately following the define is called the macro name. There is onename space for macro names. Any white-space characters preceding or following thereplacement list of preprocessing tokens are not considered part of the replacement listfor either form of macro.§6.10.3Language151ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N12568If a # preprocessing token, followed by an identifier, occurs lexically at the point at whicha preprocessing directive could begin, the identifier is not subject to macro replacement.9A preprocessing directive of the form# define identifier replacement-list new-linedefines an object-like macro that causes each subsequent instance of the macro name149)to be replaced by the replacement list of preprocessing tokens that constitute theremainder of the directive.

The replacement list is then rescanned for more macro namesas specified below.10A preprocessing directive of the form# define identifier lparen identifier-listopt ) replacement-list new-line# define identifier lparen ... ) replacement-list new-line# define identifier lparen identifier-list , ...

) replacement-list new-linedefines a function-like macro with parameters, whose use is similar syntactically to afunction call. The parameters are specified by the optional list of identifiers, whose scopeextends from their declaration in the identifier list until the new-line character thatterminates the #define preprocessing directive. Each subsequent instance of thefunction-like macro name followed by a ( as the next preprocessing token introduces thesequence of preprocessing tokens that is replaced by the replacement list in the definition(an invocation of the macro). The replaced sequence of preprocessing tokens isterminated by the matching ) preprocessing token, skipping intervening matched pairs ofleft and right parenthesis preprocessing tokens.

Within the sequence of preprocessingtokens making up an invocation of a function-like macro, new-line is considered a normalwhite-space character.11The sequence of preprocessing tokens bounded by the outside-most matching parenthesesforms the list of arguments for the function-like macro. The individual arguments withinthe list are separated by comma preprocessing tokens, but comma preprocessing tokensbetween matching inner parentheses do not separate arguments. If there are sequences ofpreprocessing tokens within the list of arguments that would otherwise act aspreprocessing directives,150) the behavior is undefined.12If there is a ...

in the identifier-list in the macro definition, then the trailing arguments,including any separating comma preprocessing tokens, are merged to form a single item:the variable arguments. The number of arguments so combined is such that, following149) Since, by macro-replacement time, all character constants and string literals are preprocessing tokens,not sequences possibly containing identifier-like subsequences (see 5.1.1.2, translation phases), theyare never scanned for macro names or parameters.150) Despite the name, a non-directive is a preprocessing directive.152Language§6.10.3WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC3merger, the number of arguments is one more than the number of parameters in the macrodefinition (excluding the ...).6.10.3.1 Argument substitution1After the arguments for the invocation of a function-like macro have been identified,argument substitution takes place.

A parameter in the replacement list, unless precededby a # or ## preprocessing token or followed by a ## preprocessing token (see below), isreplaced by the corresponding argument after all macros contained therein have beenexpanded. Before being substituted, each argument’s preprocessing tokens arecompletely macro replaced as if they formed the rest of the preprocessing file; no otherpreprocessing tokens are available.2An identifier _ _VA_ARGS_ _ that occurs in the replacement list shall be treated as if itwere a parameter, and the variable arguments shall form the preprocessing tokens used toreplace it.6.10.3.2 The # operatorConstraints1Each # preprocessing token in the replacement list for a function-like macro shall befollowed by a parameter as the next preprocessing token in the replacement list.Semantics2If, in the replacement list, a parameter is immediately preceded by a # preprocessingtoken, both are replaced by a single character string literal preprocessing token thatcontains the spelling of the preprocessing token sequence for the correspondingargument.

Each occurrence of white space between the argument’s preprocessing tokensbecomes a single space character in the character string literal. White space before thefirst preprocessing token and after the last preprocessing token composing the argumentis deleted. Otherwise, the original spelling of each preprocessing token in the argumentis retained in the character string literal, except for special handling for producing thespelling of string literals and character constants: a \ character is inserted before each "and \ character of a character constant or string literal (including the delimiting "characters), except that it is implementation-defined whether a \ character is insertedbefore the \ character beginning a universal character name. If the replacement thatresults is not a valid character string literal, the behavior is undefined.

The characterstring literal corresponding to an empty argument is "". The order of evaluation of # and## operators is unspecified.§6.10.3.2Language153ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N12566.10.3.3 The ## operatorConstraints1A ## preprocessing token shall not occur at the beginning or at the end of a replacementlist for either form of macro definition.Semantics2If, in the replacement list of a function-like macro, a parameter is immediately precededor followed by a ## preprocessing token, the parameter is replaced by the correspondingargument’s preprocessing token sequence; however, if an argument consists of nopreprocessing tokens, the parameter is replaced by a placemarker preprocessing tokeninstead.151)3For both object-like and function-like macro invocations, before the replacement list isreexamined for more macro names to replace, each instance of a ## preprocessing tokenin the replacement list (not from an argument) is deleted and the preceding preprocessingtoken is concatenated with the following preprocessing token.

Placemarkerpreprocessing tokens are handled specially: concatenation of two placemarkers results ina single placemarker preprocessing token, and concatenation of a placemarker with anon-placemarker preprocessing token results in the non-placemarker preprocessing token.If the result is not a valid preprocessing token, the behavior is undefined. The resultingtoken is available for further macro replacement. The order of evaluation of ## operatorsis unspecified.4EXAMPLEIn the following fragment:#define#define#define#definehash_hash # ## #mkstr(a) # ain_between(a) mkstr(a)join(c, d) in_between(c hash_hash d)char p[] = join(x, y); // equivalent to// char p[] = "x ## y";The expansion produces, at various stages:join(x, y)in_between(x hash_hash y)in_between(x ## y)mkstr(x ## y)"x ## y"In other words, expanding hash_hash produces a new token, consisting of two adjacent sharp signs, butthis new token is not the ## operator.151) Placemarker preprocessing tokens do not appear in the syntax because they are temporary entities thatexist only within translation phase 4.154Language§6.10.3.3WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC36.10.3.4 Rescanning and further replacement1After all parameters in the replacement list have been substituted and # and ##processing has taken place, all placemarker preprocessing tokens are removed.

Then, theresulting preprocessing token sequence is rescanned, along with all subsequentpreprocessing tokens of the source file, for more macro names to replace.2If the name of the macro being replaced is found during this scan of the replacement list(not including the rest of the source file’s preprocessing tokens), it is not replaced.Furthermore, if any nested replacements encounter the name of the macro being replaced,it is not replaced. These nonreplaced macro name preprocessing tokens are no longeravailable for further replacement even if they are later (re)examined in contexts in whichthat macro name preprocessing token would otherwise have been replaced.3The resulting completely macro-replaced preprocessing token sequence is not processedas a preprocessing directive even if it resembles one, but all pragma unary operatorexpressions within it are then processed as specified in 6.10.9 below.6.10.3.5 Scope of macro definitions1A macro definition lasts (independent of block structure) until a corresponding #undefdirective is encountered or (if none is encountered) until the end of the preprocessingtranslation unit.

Macro definitions have no significance after translation phase 4.2A preprocessing directive of the form# undef identifier new-linecauses the specified identifier no longer to be defined as a macro name. It is ignored ifthe specified identifier is not currently defined as a macro name.3EXAMPLE 1The simplest use of this facility is to define a ‘‘manifest constant’’, as in#define TABSIZE 100int table[TABSIZE];4EXAMPLE 2 The following defines a function-like macro whose value is the maximum of its arguments.It has the advantages of working for any compatible types of the arguments and of generating in-line codewithout the overhead of function calling.

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

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

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

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