为什么C预处理器认为枚举值相等? [英] Why does the C preprocessor consider enum values as equal?

查看:140
本文介绍了为什么C预处理器认为枚举值相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使 A 和<$ c $,为什么以下代码中的 std :: cout 行也会运行c> B 不同吗?

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.

问题的原因:

我想为某些测试代码提供一个模式选择器,在其中可以通过在顶部注释/取消注释行来轻松更改模式:

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.

推荐答案

没有称为 A 的宏,或者 B ,因此在您的 #if 行, A B 被替换为 0 ,因此您实际上拥有:

There are no macros called A or B, so on your #if line, A and B get replaced by 0, so you actually have:

enum T { A = 1, B = 2 };

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

预处理器在编译器对您的信息一无所知之前运行枚举。预处理器只知道宏( #define )。

The preprocessor runs before the compiler knows anything about your enum. The preprocessor only knows about macros (#define).

这篇关于为什么C预处理器认为枚举值相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆