📄 cpp.texinfo
字号:
#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.@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 thisoperation is to compute how many @samp{int}'s are needed to holda certain number of @samp{char}'s.) 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@exampleif (*p != 0) SKIP_SPACES (p, lim);else @dots{}@end example@noindentThe presence of two statements---the compound statement and a nullstatement---in between the @samp{if} condition and the @samp{else}makes invalid C code.The definition of the macro @samp{SKIP_SPACES} can be altered to solvethis problem, using a @samp{do @dots{} while} statement. Here is how:@example#define SKIP_SPACES (p, limit) \do @{ register char *lim = (limit); \ while (p != lim) @{ \ if (*p++ != ' ') @{ \ p--; break; @}@}@} \while (0)@end exampleNow @samp{SKIP_SPACES (p, lim);} expands into@exampledo @{@dots{}@} while (0);@end example@noindentwhich is one statement.@node Side Effects, Self-Reference, Swallow Semicolon, Macro Pitfalls@subsubsection Duplication of Side Effects@cindex side effects (in macro arguments)@cindex unsafe macrosMany C programs define a macro @samp{min}, for ``minimum'', like this:@example#define min(X, Y) ((X) < (Y) ? (X) : (Y))@end exampleWhen you use this macro with an argument containing a side effect,as shown here,@examplenext = min (x + y, foo (z));@end example@noindentit expands as follows:@examplenext = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));@end example@noindentwhere @samp{x + y} has been substituted for @samp{X} and @samp{foo (z)}for @samp{Y}.The function @samp{foo} is used only once in the statement as it appearsin the program, but the expression @samp{foo (z)} has been substitutedtwice into the macro expansion. As a result, @samp{foo} might be calledtwo times when the statement is executed. If it has side effects orif it takes a long time to compute, the results might not be what youintended. We say that @samp{min} is an @dfn{unsafe} macro.The best solution to this problem is to define @samp{min} in a way thatcomputes the value of @samp{foo (z)} only once. The C language offers nostandard way to do this, but it can be done with GNU C extensions asfollows:@example#define min(X, Y) \(@{ typeof (X) __x = (X), __y = (Y); \ (__x < __y) ? __x : __y; @})@end exampleIf you do not wish to use GNU C extensions, the only solution is to becareful when @emph{using} the macro @samp{min}. For example, you cancalculate the value of @samp{foo (z)}, save it in a variable, and use thatvariable in @samp{min}:@example#define min(X, Y) ((X) < (Y) ? (X) : (Y))@dots{}@{ int tem = foo (z); next = min (x + y, tem);@}@end example@noindent(where I assume that @samp{foo} returns type @samp{int}).@node Self-Reference, Argument Prescan, Side Effects, Macro Pitfalls@subsubsection Self-Referential Macros@cindex self-referenceA @dfn{self-referential} macro is one whose name appears in its definition.A special feature of ANSI Standard C is that the self-reference is notconsidered a macro call. It is passed into the preprocessor outputunchanged.Let's consider an example:@example#define foo (4 + foo)@end example@noindentwhere @samp{foo} is also a variable in your program.Following the ordinary rules, each reference to @samp{foo} will expand into@samp{(4 + foo)}; then this will be rescanned and will expand into @samp{(4+ (4 + foo))}; and so on until it causes a fatal error (memory full) in thepreprocessor.However, the special rule about self-reference cuts this process shortafter one step, at @samp{(4 + foo)}. Therefore, this macro definitionhas the possibly useful effect of causing the program to add 4 tothe value of @samp{foo} wherever @samp{foo} is referred to.In most cases, it is a bad idea to take advantage of this feature. Aperson reading the program who sees that @samp{foo} is a variable willnot expect that it is a macro as well. The reader will come across theidentifier @samp{foo} in the program and think its value should be thatof the variable @samp{foo}, whereas in fact the value is four greater.The special rule for self-reference applies also to @dfn{indirect}self-reference. This is the case where a macro @var{x} expands to use amacro @samp{y}, and @samp{y}'s expansion refers to the macro @samp{x}. Theresulting reference to @samp{x} comes indirectly from the expansion of@samp{x}, so it is a self-reference and is not further expanded. Thus,after
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -