理解C预处理器宏的输出与行代码
#define AD(x,y) (x+y)
int main()
{
int x1=5,y1=2,z1;
int x2=5,y2=2,z2;
z1 = AD(x1,++y1);
z2 = (x2+++y2) ;
printf("%d %d %dn",x1,y1,z1);
printf("%d %d %dn",x2,y2,z2);
}
为什么输出不同?第一种情况是:5 3 8 第二种情况是:6 2 7
回答
这个表情
z2=x2+++y2;
由编译器解析,如
z2 = x2++ + y2;
来自 C 标准(6.4 词法元素)
4 如果输入流已被解析为最多给定字符的预处理标记,则下一个预处理标记是可以构成预处理标记的最长字符序列。
所以这些标记+++
被解析为++
和+
。带有宏的表达式
z1=AD(x1,++y1);
由编译器解析,如
z1 = x1 + ++y1;
编译器已经形成的这些组的令牌x1
和++y1
由于令牌之间的逗号。
所以这两种说法是不同的。
- @fred: the preprocessor is not "text replacement". It is *token* replacement. The text has already been tokenised before the preprocessing phases, and what emerges from the preprocessor is a modified stream of tokens. Aside from the actions of the stringify and token concatenation operators (`#` and `##`), every token in the output corresponds to an input token. The fact that some programs described as preprocessors produce a textual output, it's important to not be misled by that. Internally, the compiler is working on a token stream.