#include <stdio.h>
#define X (Y+4)
#define Y (X+3)
int main(void) {
printf("%d\n",4*X+2);
return 0;
}
错误: undefined symbol “X”。
最佳答案
宏扩展不会递归地重新扩展宏名称。
引用C标准:
If 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 longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.
X
扩展为 (Y + 4)
。预处理器然后尝试扩展 Y
,但是由于 Y
的扩展引用了 X
,它不会再次扩展它,留下 X
到位。
此规则避免了宏扩展中的无限递归(如果没有此规则,您的示例中就会出现这种情况)。
宏展开后,行
printf("%d\n",4*X+2);
决议:
printf("%d\n",4*((X+3) +4)+2);
由于 X
没有以在预处理器外部可见的方式定义,因此您会遇到编译时错误。
关于c - 为什么 X 在此代码中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23161068/