Why does the C preprocessor consider enum values a

2019-03-10 12:08发布

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

#include <iostream>

enum T { A = 1, B = 2 };
// #define A 1
// #define B 2

int main() {
#if (A == B)
    std::cout << A << B;
#endif
}

If I use #define instead (as commented out), I get no output as I expect.

Reason for the question:

I want to have a mode selector for some test code in which I can easily change modes by commenting/uncommenting lines on top:

enum T { MODE_RGB = 1, MODE_GREY = 2, MODE_CMYK = 3 };
// #define MODE MODE_RGB
#define MODE MODE_GREY
// #define MODE MODE_CMYK

int main() {
#if (MODE == MODE_RGB)
    // do RGB stuff
#elif (MODE == MODE_GREY)
    // do greyscale stuff
#else
    // do CMYK stuff
#endif

    // some common code

    some_function(arg1, arg2,
#if (MODE == MODE_RGB)
        // RGB calculation for arg3,
#elif (MODE == MODE_GREY)
        // greyscale calculation for arg3,
#else
        // CMYK calculation for arg3,
#endif
        arg4, arg5);
}

I know I can use numeric values e.g.

#define MODE 1 // RGB
...
#if (MODE == 1) // RGB

but it makes the code less readable.

Is there an elegant solution for this?

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-10 12:58

Other answers explain why what you're trying doesn't work; for an alternative, I'd probably go with:

#define RGB 1
#define GREY 2
#define CMYK 3
#define MODE RGB

#if MODE == RGB
    //RGB-mode code
#elif MODE == GREY
    //Greyscale code
#elif MODE == CMYK
    //CMYK code
#else
#    error Undefined MODE
#endif

You might want prefixes on the RGB/GREY/CMYK if there's a danger of clashes with "real" source code.

查看更多
登录 后发表回答