C++ 中的预处理器指令:以下代码的输出是什么?

Preprocessors Directives in c++ : what is the output of the following code?

同学们。我有以下代码,但我对它的输出感到困惑。当我 运行 这段代码时,它告诉我 C 将是 2,但我虽然它是 0。为什么是 2?泰!

#include <iostream>
using namespace std;

#define A    0
#define B    A+1 
#define C    1-B

int main() {
cout<<C<<endl;
return 0;
}

这里的要点是您期望 BA 之前被评估。普通 C++ 代码也是如此,但预处理器只是 替换 指令及其内容。

在这种情况下,会发生如下情况。取:

cout<<C<<endl;

C代替1-B:

cout<<1-B<<endl;

B -> A+1

cout<<1-A+1<<endl;

A -> 0

cout<<1-0+1<<endl;

按照通常的rules of C++ operator precedence-+是相等的,从左到右关联,所以,1 - 0 + 1就是2

对于 gcc,使用 -E 标志查看预处理后的输出。

删除包含和其余代码以查看此输出:

#define A    0
#define B    A+1 
#define C    1-B

A
B
C

to come out as:

0
0 +1
1-0 +1

预处理器只是文本替换。如果你想定义常量然后定义常量:

const int A = 0;
const int B = A+1;
const int C = 1-B;