C++ 奇怪行为 Visual Studio
C++ Strange Behavior Visual Studio
此代码输出 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;
}
正在查看 conditional directives 页面。我发现:
The defined directive can be used in an #if and an #elif directive,
but nowhere else.
将您的代码更改为:
#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
输出
此代码输出 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;
}
正在查看 conditional directives 页面。我发现:
The defined directive can be used in an #if and an #elif directive, but nowhere else.
将您的代码更改为:
#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
输出