运行以下代码
#include <iostream> #define FOO #define BAR defined(FOO) int main() { #if BAR std::cout << "BAR enabled!" << std::endl; #else std::cout << "BAR disabled!" << std::endl; #endif return 0; }
在Visual Studio中显示Bar disabled!,在gcc或clang中运行相同的代码时显示Bar enabled!.
这是Microsoft编译器中的错误吗?根据标准,什么是正确的?
解决方法
根据标准,这是未定义的行为.
[cpp.cond],强调我的
Prior to evaluation,macro invocations in the list of preprocessing tokens that will become the controlling constant expression are replaced (except for those macro names modified by the
defined
unary operator),just as in normal text. If the tokendefined
is generated as a result of this replacement process or use of thedefined
unary operator does not match one of the two specified forms prior to macro replacement,the behavior is undefined.