c – MSVC未正确评估定义(VARIABLE)?

前端之家收集整理的这篇文章主要介绍了c – MSVC未正确评估定义(VARIABLE)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
运行以下代码
#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!,在gccclang中运行相同的代码显示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 token defined is generated as a result of this replacement process or use of the defined unary operator does not match one of the two specified forms prior to macro replacement,the behavior is undefined.

猜你在找的C&C++相关文章