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?
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
definedunary operator), just as in normal text. If the tokendefinedis generated as a result of this replacement process or use of thedefinedunary operator does not match one of the two specified forms prior to macro replacement, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With