【问题标题】:C++ Strange Behavior Visual StudioC++ 奇怪行为 Visual Studio
【发布时间】:2015-03-12 12:04:37
【问题描述】:

此代码为 Visual Studio 2012 和 2008 输出 T2、T4,为 gcc 输出 T1、T2、T3、T4。 是什么原因?

#include <iostream>

#define ABC

#define T1 defined(ABC)

#define T2 defined( ABC )

#define T3 defined(ABC )

#define T4 defined( ABC)


int main(int argc, char* argv[])
{

#if T1

    std::cout<<"T1"<<std::endl;
#endif


#if T2

    std::cout<<"T2"<<std::endl;
#endif


#if T3

    std::cout<<"T3"<<std::endl;
#endif


#if T4

    std::cout<<"T4"<<std::endl;
#endif

    return 0;
}

【问题讨论】:

  • 您为什么不能使用实时预览来检查您的帖子是否正常?
  • 没有找到如何逃避尖锐符号。
  • 使用 keep pre-processed 选项运行两个编译器并查看它们的输出
  • 嗯,在 vs2013 中我只得到 T2

标签: c++ visual-studio visual-studio-2012 defined


【解决方案1】:

查看conditional directives 页面。我发现:

定义的指令可以用在#if 和#elif 指令中, 但别无他处。

将代码更改为:

#include <iostream>

#define ABC

int main(int argc, char* argv[])
{

#if defined(ABC)
    std::cout << "T1" << std::endl;
#endif


#if defined( ABC )
    std::cout << "T2" << std::endl;
#endif


#if defined(ABC )
    std::cout << "T3" << std::endl;
#endif


#if defined( ABC)
    std::cout << "T4" << std::endl;
#endif

    return 0;
}

将在 VS 2013 中产生 T1,T2,T3,T4 输出

【讨论】:

  • 从这个描述:en.cppreference.com/w/cpp/preprocessor/conditional 事实证明,“定义”处理在宏扩展之前进行,而宏扩展在表达式评估之前进行。这是否意味着扩展宏中的“已定义”是未定义的行为,并且可能导致任何结果,包括用 0 替换整个“已定义”调用、语法错误或其他什么?没有任何已知问题吗?
  • 找到它:gcc.gnu.org/onlinedocs/cpp/Defined.html - 它确实被声明为未定义的行为
猜你喜欢
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多