📄 cpp.texi
字号:
The stringification feature is limited to transforming one macro argumentinto one string constant: there is no way to combine the argument withother text and then stringify it all together. But the example above showshow an equivalent result can be obtained in ANSI Standard C using thefeature that adjacent string constants are concatenated as one stringconstant. The preprocessor stringifies the actual value of @samp{EXP} into a separate string constant, resulting in text like@smallexampledo @{ if (x == 0) \ fprintf (stderr, "Warning: " "x == 0" "\n"); @} \while (0)@end smallexample@noindentbut the C compiler then sees three consecutive string constants andconcatenates them into one, producing effectively@smallexampledo @{ if (x == 0) \ fprintf (stderr, "Warning: x == 0\n"); @} \while (0)@end smallexampleStringification in C involves more than putting doublequote charactersaround the fragment; it is necessary to put backslashes in front of alldoublequote characters, and all backslashes in string and characterconstants, in order to get a valid C string constant with the propercontents. Thus, stringifying @samp{p = "foo\n";} results in @samp{"p =\"foo\\n\";"}. However, backslashes that are not inside of string orcharacter constants are not duplicated: @samp{\n} by itself stringifies to@samp{"\n"}.Whitespace (including comments) in the text being stringified is handledaccording to precise rules. All leading and trailing whitespace is ignored.Any sequence of whitespace in the middle of the text is converted toa single space in the stringified result.@node Concatenation, Undefining, Stringification, Macros@subsection Concatenation@cindex concatenation@dfn{Concatenation} means joining two strings into one. In the contextof macro expansion, concatenation refers to joining two lexical unitsinto one longer one. Specifically, an actual argument to the macro can beconcatenated with another actual argument or with fixed text to producea longer name. The longer name might be the name of a function,variable or type, or a C keyword; it might even be the name of anothermacro, in which case it will be expanded.When you define a macro, you request concatenation with the specialoperator @samp{##} in the macro body. When the macro is called,after actual arguments are substituted, all @samp{##} operators aredeleted, and so is any whitespace next to them (including whitespacethat was part of an actual argument). The result is to concatenatethe syntactic tokens on either side of the @samp{##}.Consider a C program that interprets named commands. There probably needsto be a table of commands, perhaps an array of structures declared asfollows:@examplestruct command@{ char *name; void (*function) ();@};struct command commands[] =@{ @{ "quit", quit_command@}, @{ "help", help_command@}, @dots{}@};@end exampleIt would be cleaner not to have to give each command name twice, once inthe string constant and once in the function name. A macro which takes thename of a command as an argument can make this unnecessary. The stringconstant can be created with stringification, and the function name byconcatenating the argument with @samp{_command}. Here is how it is done:@example#define COMMAND(NAME) @{ #NAME, NAME ## _command @}struct command commands[] =@{ COMMAND (quit), COMMAND (help), @dots{}@};@end exampleThe usual case of concatenation is concatenating two names (or a name and anumber) into a longer name. But this isn't the only valid case. It isalso possible to concatenate two numbers (or a number and a name, such as@samp{1.5} and @samp{e3}) into a number. Also, multi-character operatorssuch as @samp{+=} can be formed by concatenation. In some cases it is evenpossible to piece together a string constant. However, two pieces of textthat don't together form a valid lexical unit cannot be concatenated. Forexample, concatenation with @samp{x} on one side and @samp{+} on the otheris not meaningful because those two characters can't fit together in anylexical unit of C. The ANSI standard says that such attempts atconcatenation are undefined, but in the GNU C preprocessor it is welldefined: it puts the @samp{x} and @samp{+} side by side with no particularspecial results.Keep in mind that the C preprocessor converts comments to whitespace beforemacros are even considered. Therefore, you cannot create a comment byconcatenating @samp{/} and @samp{*}: the @samp{/*} sequence that starts acomment is not a lexical unit, but rather the beginning of a ``long'' spacecharacter. Also, you can freely use comments next to a @samp{##} in amacro definition, or in actual arguments that will be concatenated, becausethe comments will be converted to spaces at first sight, and concatenationwill later discard the spaces.@node Undefining, Redefining, Concatenation, Macros@subsection Undefining Macros@cindex undefining macrosTo @dfn{undefine} a macro means to cancel its definition. This is donewith the @samp{#undef} command. @samp{#undef} is followed by the macroname to be undefined.Like definition, undefinition occurs at a specific point in the sourcefile, and it applies starting from that point. The name ceases to be amacro name, and from that point on it is treated by the preprocessor as ifit had never been a macro name.For example,@example#define FOO 4x = FOO;#undef FOOx = FOO;@end example@noindentexpands into@examplex = 4;x = FOO;@end example@noindentIn this example, @samp{FOO} had better be a variable or function as wellas (temporarily) a macro, in order for the result of the expansion to bevalid C code.The same form of @samp{#undef} command will cancel definitions witharguments or definitions that don't expect arguments. The @samp{#undef}command has no effect when used on a name not currently defined as a macro.@node Redefining, Macro Pitfalls, Undefining, Macros@subsection Redefining Macros@cindex redefining macros@dfn{Redefining} a macro means defining (with @samp{#define}) a name thatis already defined as a macro.A redefinition is trivial if the new definition is transparently identicalto the old one. You probably wouldn't deliberately write a trivialredefinition, but they can happen automatically when a header file isincluded more than once (@pxref{Header Files}), so they are acceptedsilently and without effect.Nontrivial redefinition is considered likely to be an error, soit provokes a warning message from the preprocessor. However, sometimes itis useful to change the definition of a macro in mid-compilation. You caninhibit the warning by undefining the macro with @samp{#undef} before thesecond definition.In order for a redefinition to be trivial, the new definition mustexactly match the one already in effect, with two possible exceptions:@itemize @bullet@itemWhitespace may be added or deleted at the beginning or the end.@itemWhitespace may be changed in the middle (but not inside strings).However, it may not be eliminated entirely, and it may not be addedwhere there was no whitespace at all.@end itemizeRecall that a comment counts as whitespace.@node Macro Pitfalls,, Redefining, Macros@subsection Pitfalls and Subtleties of MacrosIn this section we describe some special rules that apply to macros andmacro expansion, and point out certain cases in which the rules havecounterintuitive consequences that you must watch out for.@menu* Misnesting:: Macros can contain unmatched parentheses.* Macro Parentheses:: Why apparently superfluous parentheses may be necessary to avoid incorrect grouping.* Swallow Semicolon:: Macros that look like functions but expand into compound statements.* Side Effects:: Unsafe macros that cause trouble when arguments contain side effects.* Self-Reference:: Macros whose definitions use the macros' own names.* Argument Prescan:: Actual arguments are checked for macro calls before they are substituted.* Cascaded Macros:: Macros whose definitions use other macros.* Newlines in Args:: Sometimes line numbers get confused.@end menu@node Misnesting, Macro Parentheses, Macro Pitfalls, Macro Pitfalls@subsubsection Improperly Nested ConstructsRecall that when a macro is called with arguments, the arguments aresubstituted into the macro body and the result is checked, together withthe rest of the input file, for more macro calls.It is possible to piece together a macro call coming partially from themacro body and partially from the actual arguments. For example,@example#define double(x) (2*(x))#define call_with_1(x) x(1)@end example@noindentwould expand @samp{call_with_1 (double)} into @samp{(2*(1))}.Macro definitions do not have to have balanced parentheses. By writing anunbalanced open parenthesis in a macro body, it is possible to create amacro call that begins inside the macro body but ends outside of it. Forexample,@example#define strange(file) fprintf (file, "%s %d",@dots{}strange(stderr) p, 35)@end example@noindentThis bizarre example expands to @samp{fprintf (stderr, "%s %d", p, 35)}!@node Macro Parentheses, Swallow Semicolon, Misnesting, Macro Pitfalls@subsubsection Unintended Grouping of ArithmeticYou may have noticed that in most of the macro definition examples shownabove, each occurrence of a macro argument name had parentheses around it.In addition, another pair of parentheses usually surround the entire macrodefinition. Here is why it is best to write macros that way.Suppose you define a macro as follows,@example#define ceil_div(x, y) (x + y - 1) / y@end example@noindentwhose purpose is to divide, rounding up. (One use for this operation isto compute how many @samp{int} objects are needed to hold a certainnumber of @samp{char} objects.) Then suppose it is used as follows:@examplea = ceil_div (b & c, sizeof (int));@end example@noindentThis expands into@examplea = (b & c + sizeof (int) - 1) / sizeof (int);@end example@noindentwhich does not do what is intended. The operator-precedence rules ofC make it equivalent to this:@examplea = (b & (c + sizeof (int) - 1)) / sizeof (int);@end example@noindentBut what we want is this:@examplea = ((b & c) + sizeof (int) - 1)) / sizeof (int);@end example@noindentDefining the macro as@example#define ceil_div(x, y) ((x) + (y) - 1) / (y)@end example@noindentprovides the desired result.However, unintended grouping can result in another way. Consider@samp{sizeof ceil_div(1, 2)}. That has the appearance of a C expressionthat would compute the size of the type of @samp{ceil_div (1, 2)}, but infact it means something very different. Here is what it expands to:@examplesizeof ((1) + (2) - 1) / (2)@end example@noindentThis would take the size of an integer and divide it by two. The precedencerules have put the division outside the @samp{sizeof} when it was intendedto be inside.Parentheses around the entire macro definition can prevent such problems.Here, then, is the recommended way to define @samp{ceil_div}:@example#define ceil_div(x, y) (((x) + (y) - 1) / (y))@end example@node Swallow Semicolon, Side Effects, Macro Parentheses, Macro Pitfalls@subsubsection Swallowing the Semicolon@cindex semicolons (after macro calls)Often it is desirable to define a macro that expands into a compoundstatement. Consider, for example, the following macro, that advances apointer (the argument @samp{p} says where to find it) across whitespacecharacters:@example#define SKIP_SPACES (p, limit) \@{ register char *lim = (limit); \ while (p != lim) @{ \ if (*p++ != ' ') @{ \ p--; break; @}@}@}@end example@noindentHere Backslash-Newline is used to split the macro definition, which mustbe a single line, so that it resembles the way such C code would belaid out if not part of a macro definition.A call to this macro might be @samp{SKIP_SPACES (p, lim)}. Strictlyspeaking, the call expands to a compound statement, which is a completestatement with no need for a semicolon to end it. But it looks like afunction call. So it minimizes confusion if you can use it like a functioncall, writing a semicolon afterward, as in @samp{SKIP_SPACES (p, lim);}But this can cause trouble before @samp{else} statements, because thesemicolon is actually a null statement. Suppose you write
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -