且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

c语言中的宏求值

更新时间:2023-02-18 16:07:06

由于预处理器执行操作的顺序不同,输出不同,这在 C99 标准中的第 6.10.3 节(以及以下)中进行了描述.特别是6.10.3.1/1中的这句话:

The output is different because of the order in which the preprocessor does things, which is described in section 6.10.3 (and those following) in the C99 standard. In particular, this sentence from 6.10.3.1/1:

替换列表中的参数,除非前面有 ### 预处理标记或后跟 ## 预处理标记,在其中包含的所有宏都已展开后,由相应的参数替换.

A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token, is replaced by the corresponding argument after all macros contained therein have been expanded.

所以在第一行中,当扩展h的调用时,参数f(1,2)被扩展之前它替换h 的参数 a.# 仅在稍后在重新扫描所有输出时看到对 g 的结果调用时才起作用.

So in the first line, when expanding the invocation of h, the argument f(1,2) is expanded before it replaces h's parameter a. The # only comes into play later when the resulting invocation of g is seen when the output of all that is rescanned.

但是在第二行,立即看到 # 并且上面引用的除非前面有..."子句触发了不同的行为.

But on the second line, the # is seen immediately and the "unless preceded by..." clause of the quotation above triggers the different behaviour.

另请参阅相关的 C-FAQ 条目.