Search code examples
c++visual-studiovisual-studio-2012defined

C++ Strange Behavior Visual Studio


This code outputs T2, T4 for Visual Studio 2012 and 2008 and T1,T2,T3,T4 for gcc. What's the reason?

#include <iostream>

#define ABC

#define T1 defined(ABC)

#define T2 defined( ABC )

#define T3 defined(ABC )

#define T4 defined( ABC)


int main(int argc, char* argv[])
{

#if T1

    std::cout<<"T1"<<std::endl;
#endif


#if T2

    std::cout<<"T2"<<std::endl;
#endif


#if T3

    std::cout<<"T3"<<std::endl;
#endif


#if T4

    std::cout<<"T4"<<std::endl;
#endif

    return 0;
}

Solution

  • Looking at conditional directives page. I've found that:

    The defined directive can be used in an #if and an #elif directive, but nowhere else.

    Changing your code to:

    #include <iostream>
    
    #define ABC
    
    int main(int argc, char* argv[])
    {
    
    #if defined(ABC)
        std::cout << "T1" << std::endl;
    #endif
    
    
    #if defined( ABC )
        std::cout << "T2" << std::endl;
    #endif
    
    
    #if defined(ABC )
        std::cout << "T3" << std::endl;
    #endif
    
    
    #if defined( ABC)
        std::cout << "T4" << std::endl;
    #endif
    
        return 0;
    }
    

    Will produce T1,T2,T3,T4 output in VS 2013