c - 为什么 X 在此代码中未定义?

标签 c c-preprocessor

#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/

相关文章:

c - 对二维数组求和

c - 程序执行是否总是从 C 中的 main 开始?

c - 从 C 中的函数返回多个值

C++预处理器+检测对象类型和new操作

c++ - 使用 BOOST_PP_SEQ_FOREACH_R 递归处理枚举

c - 查看扩展的 C 宏

c - 用 define C 替换函数调用(而不是声明)

c - 点到平面的投影

c - 从 C 库返回到 GNU COBOL 的不可打印整数指针

c++ - FSEvents C++ 示例