defined(VARIABLE) not evaluated correctly by MSVC?

大兔子大兔子 提交于 2019-12-19 18:54:12

问题


Running the following code

#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;
}

in Visual Studio displays Bar disabled!, while running the same code in gcc or clang displays Bar enabled!.

Is this a bug in the Microsoft compiler? What is correct according to the standard?


回答1:


This is undefined behavior according to the standard.

[cpp.cond], emphasis mine

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.



来源:https://stackoverflow.com/questions/38355289/definedvariable-not-evaluated-correctly-by-msvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!