简体   繁体   English

#define的奇怪行为

[英]Odd behavior by #define

I have this code in C++: 我在C ++中有以下代码:

#include <string>
#include <iostream>

int const foo = 1;
int const bar = 0;

#define foo bar
#define bar foo

int main()
{
  std::cout << foo << std::endl;
  std::cout << bar << std::endl;
}

It produces this output: 它产生以下输出:

bash-3.2$ ./a.out
1
0

I do not understand why this is the output. 我不明白为什么这是输出。

Macros will never expand recursively. 宏永远不会递归扩展。

When you write foo , it first expands to bar , and then since bar is a macro it expands back to foo . 当您编写foo ,它首先扩展为bar ,然后由于bar是一个宏,因此它会扩展回foo While foo is a macro, because macros can't be recursive it will not be expanded. 尽管foo是一个宏,但由于宏不能递归,因此它不会被扩展。 And then evaluating foo yields its value: 1. 然后评估foo得出其值:1。

The same goes for bar . bar

See this: http://gcc.gnu.org/onlinedocs/cpp/Self_002dReferential-Macros.html#Self_002dReferential-Macros 看到这个: http : //gcc.gnu.org/onlinedocs/cpp/Self_002dReferential-Macros.html#Self_002dReferential-Macros

And ISO/IEC 14882:2003(E) 16.3.4 Rescanning and further replacement section of the standard. 以及ISO / IEC 14882:2003(E)16.3.4标准的重新扫描和进一步替换部分。 (see comments for more details) (请参阅评论以获取更多详细信息)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM