Is #if defined MACRO equivalent to #ifdef MACRO?

后端 未结 5 1133
自闭症患者
自闭症患者 2020-12-08 21:38

I have code that I want to have two modes, debug and verbose. I define them in my header file as,

#define verbose TRUE
#def         


        
5条回答
  •  醉梦人生
    2020-12-08 22:01

    No, they are not at all equivalent. An #if MACRO branch is compiled if MACRO evaluates to non-zero. On the other hand, an #ifdef MACRO branch is compiled if MACRO is defined, no matter what it evaluates to. So

    #include 
    
    #define VAR_SET_TO_TRUE 1
    #define VAR_SET_TO_FALSE 0
    
    int main()
    {
    
    #if VAR_SET_TO_TRUE
        printf("#if VAR_SET_TO_TRUE\n");
    #endif
    
    #if VAR_SET_TO_FALSE
        printf("#if VAR_SET_TO_FALSE\n");
    #endif
    
    #if VAR_UNSET
        printf("#if VAR_UNSET\n");
    #endif
    
    
    
    #ifdef VAR_SET_TO_TRUE
        printf("#ifdef VAR_SET_TO_TRUE\n");
    #endif
    
    #ifdef VAR_SET_TO_FALSE
        printf("#ifdef VAR_SET_TO_FALSE\n");
    #endif
    
    #ifdef VAR_UNSET
        printf("#ifdef VAR_UNSET\n");
    #endif
    
    }
    

    will output

    #if VAR_SET_TO_TRUE
    #ifdef VAR_SET_TO_TRUE
    #ifdef VAR_SET_TO_FALSE
    

    Note that the line printf("#ifdef VAR_SET_TO_FALSE\n"); is compiled while the line printf("#if VAR_SET_TO_FALSE\n"); is not. The first one is compiled, because VAR_SET_TO_FALSE is defined, even though its value is false.

提交回复
热议问题