简体   繁体   English

为什么我不能使用#if来比较宏和枚举?

[英]Why cant I compare macro and enum using #if?

I am trying to check using #if, that a macro and enum are equal or not. 我试图使用#if检查宏和枚举是否相等。 the check fails even if both has same value. 即使两者具有相同的值,检查也会失败。 why? 为什么?

Created a macro using #define NUMBER 2. Created enum including one entry with value 2. compared both using #if . 使用#define NUMBER创建一个宏2.创建枚举,包括一个值为2的条目。使用#if进行比较。 compared macro with 2 is getting passed. 比较宏与2比较过。 but comparing macro with enum fails. 但是将宏与枚举进行比较失败了。

#include <stdio.h>
#define NUMBER 2
enum numbers
{
    zero = 0, 
    one, 
    two, 
    three
};

int main ()
{
    printf("NUMBER: %x and two: %x\n", NUMBER, two);

#if NUMBER == two
    printf("#1-------PASS\n");
#else
    printf("#1--------FAIL\n");
#endif

#if NUMBER == 2
    printf("#2-------PASS\n");
#else
    printf("#2--------FAIL\n");
#endif

    if (NUMBER == two)
        printf("#3-------PASS\n");
    else
        printf("#3--------FAIL\n");
}

I expected PASS for all three cases. 我预计所有三个案件的通行证。 Actual result: 实际结果:

NUMBER: 2 and two: 2
#1--------FAIL
#2-------PASS
#3-------PASS

The handling of #if and macros is done during the early translation phases of a C program. #if和宏的处理是在C程序的早期翻译阶段完成的。 Ie it's done during "preprocessing". 即它是在“预处理”期间完成的。 During those phases there is no notion of enumerators (which are handled much later). 在这些阶段期间,没有调查员的概念(稍后处理)。 The preprocessor deals only in tokens, and substituting one token for zero or more other tokens is all it can really do at that stage. 预处理器只处理令牌,用一个令牌代替零个或多个其他令牌就是它在那个阶段真正可以做的。 An enumeration is a semantic construct, more than just token soup, so again, the preprocessor knows nothing about it. 枚举是一种语义结构,不仅仅是令牌汤,因此预处理器一无所知。

When you use two , the preprocessor will treat it as a preprocessing token, same as it treats NUMBER . 当您使用two ,预处理器会将其视为预处理令牌,与处理NUMBER相同。 It will try to substitute it to produce some valid condition. 它会尝试用它来代替它来产生一些有效的条件。 But it wasn't #define d, so it uses a fallback behavior. 但它不是#define d,所以它使用了回退行为。 Every token that isn't defined but used in an #if , is substituted with 0. The condition being checked ends up being therefore: 未定义但在#if使用的每个标记都被替换为0.因此检查的条件最终为:

#if 2 == 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM