Why does the C preprocessor consider enum values as equal?

后端 未结 7 1328
南方客
南方客 2020-12-08 12:48

Why does the std::cout line in the following code run even though A and B are different?

#include 

en         


        
7条回答
  •  孤城傲影
    2020-12-08 13:27

    This is because the preprocessor works before compile time.

    As the enum definitions occur at compile time, A and B will both be defined as empty (pp-number 0) - and thus equal - at pre-processing time, and thus the output statement is included in the compiled code.

    When you use #define they are defined differently at pre-processing time and thus the statement evaluates to false.

    In relation to your comment about what you want to do, you don't need to use pre-processor #if to do this. You can just use the standard if as both MODE and MODE_GREY (or MODE_RGB or MODE_CMYK) are all still defined:

    #include 
    
    enum T { MODE_RGB = 1, MODE_GREY = 2, MODE_CMYK = 3 };
    
    #define MODE MODE_GREY
    
    int main()
    {
        if( MODE == MODE_GREY )
            std::cout << "Grey mode" << std::endl;
        else if( MODE == MODE_RGB )
            std::cout << "RGB mode" << std::endl;
        else if( MODE == MODE_CMYK )
            std::cout << "CMYK mode" << std::endl;
    
        return 0;
    }
    

    The other option using only the pre-processor is to do this as @TripeHound correctly answered below.

提交回复
热议问题