【问题标题】:Preprocessors Directives in c++ : what is the output of the following code?c++ 中的预处理器指令:以下代码的输出是什么?
【发布时间】:2020-12-03 19:31:52
【问题描述】:

这里的学生。我有以下一段代码,我对它的输出感到困惑。当我运行这段代码时,它告诉我 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;
}

【问题讨论】:

  • #define 语句只是预处理器的纯文本替换,因此C 将替换为1-0+1,在编译器评估时为2。尝试使用#define B (A+1)#define C 1-(B),然后C 将被替换为1-(0+1),其值为0。
  • #define C 1-(B)比较。
  • fwiw,不只是你对此感到困惑。
  • 因为您在完全展开表达式后评估它:)
  • 这是一个很好的理由,不要使用#define 作为常量,而是使用实际的 C++ 语言常量,例如:const int A = 0; const int B = A+1; const int C = 1-B;

标签: c++ preprocessor-directive


【解决方案1】:

这里的要点是,您希望在 A 之前评估 B。对于普通的 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 + 12

【讨论】:

    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多