Why does the C preprocessor consider enum values as equal?

后端 未结 7 1329
南方客
南方客 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 13:43

    The posts have explained why, but a possible solution for you that keeps readability might be like this

    #define MODE_RGB
    
    int main()
    {        
        #ifdef MODE_RGB
            std::cout << "RGB mode" << std::endl;
        #elif defined MODE_GREY
            std::cout << "Grey mode" << std::endl;
        #elif defined MODE_CMYK
            std::cout << "CMYK mode" << std::endl;
        #endif
    }
    

    You just then need to change the macro at the top, to only the macro you are interested in is defined. You could also include a check to make sure that one and only one is defined and if not then and do #error "You must define MODE_RGB, MODE_GREY or MODE_CMYK

提交回复
热议问题