Jan Rüegg
Jan Rüegg

Reputation: 10075

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?

Upvotes: 6

Views: 156

Answers (1)

cpplearner
cpplearner

Reputation: 15918

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.

Upvotes: 8

Related Questions