Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an error when directly comparing two enums?

I have some code I'm porting to a new platform, and it started giving me an error about comparing two enumerators from two different enumerator-lists. I'm confused why it's giving me an error about this.

The enumeration specificers section of the C spec (6.7.2.2) states:

The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted.127) An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no =, the value of its enumeration constant is 0.

So I should be able to use enum members the same as int constants. In this small sample program:

enum first {
  a,
  b
};

enum second {
 c,
 d
};

int main(){
    enum first myf = a;
    enum second mys = c;

    if(myf == mys)
        printf("same value\n"); 
    return 0;
}

When compiled with gcc -Wall -Werror I get the message:

error: comparison between ‘enum first’ and ‘enum second’ [-Werror=enum-compare]

I know that if I typecast both myf and mys as ints the compiler will be happy, just like I could set a couple of ints with the values from myf and mys and do the comparison; but why do I have to do either of these to get rid of the warning? Why does this warning exist in the first place? There must be some danger in doing this that I'm not seeing.


NOTE:
I have read the gcc documentation on this enum-compare flag, but it doesn't say much of anything:

-Wenum-compare
Warn about a comparison between values of different enumerated types. In C++ enumeral mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by -Wall.

like image 325
Mike Avatar asked Apr 02 '13 19:04

Mike


1 Answers

if((int)myf == (int)mys)

That should do it. But it is dirty practice, only use it if both enums are different "versions" of the same group, like the newer one would contain new keywords at the end.

like image 93
Zdenek Avatar answered Oct 15 '22 09:10

Zdenek