gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:35:00 26 4
gpt4 key购买 nike

考虑以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com