Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defined(VARIABLE) not evaluated correctly by MSVC?

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?

like image 277
Jan Rüegg Avatar asked Jul 13 '16 15:07

Jan Rüegg


1 Answers

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.

like image 169
cpplearner Avatar answered Sep 29 '22 10:09

cpplearner