c++ - C++宏中相互引用的奇怪结果

标签 c++ c-preprocessor

考虑以下 C++ 代码:

#include <bits/stdc++.h>
using namespace std;

string TRUE = "true";
string FALSE = "false";

#define TRUE FALSE
#define FALSE TRUE

int main()
{
    cout << TRUE << endl;
    cout << FALSE << endl;
}

使用GCC 4.9.2编译,以上代码输出:

true
false

产生的输出背后的逻辑是什么?我期待“false\ntrue\n”甚至“false\nfalse\n”,但我找不到这个实际输出背后的原因。

这对#defines 在这种情况下是如何工作的?

最佳答案

这在 [cpp.rescan]/1-2 中有描述:

16.3.4 Rescanning and further replacement

  1. After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. Then the resulting preprocessing token sequence is rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.
  2. 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.

(强调我的)

所以:当代码中遇到 TRUE 时,将其替换为 FALSE。序列被重新扫描,FALSE 被替换为 TRUE。序列被重新扫描,发现 TRUE 但不再符合替换条件,因此它保留下来。这同样适用于 FALSE 的扩展(带有交换的标识符)。

关于c++ - C++宏中相互引用的奇怪结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29183016/

相关文章:

c++ - 从 C 数组创建特征矩阵

c++ - C/C++ 中的#error 是如何工作的?

c++ - C 预处理器 - 现有定义的前置路径

C 预处理器宏扩展

C++ 预处理器条件参数

c++ - 如何在 DirectX 中标准化模型大小?

c++ - Boost::任何对存储值的引用都无法编译

c - 如何在 C 中使用单个赋值来定义多个 #define

c++ - 在 C++ 中添加整数输出?

c++ - 宏中的静态变量