简体   繁体   中英

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. 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 . compared macro with 2 is getting passed. 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. 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 . It will try to substitute it to produce some valid condition. But it wasn't #define d, so it uses a fallback behavior. Every token that isn't defined but used in an #if , is substituted with 0. The condition being checked ends up being therefore:

#if 2 == 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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