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

后端 未结 4 1816
闹比i
闹比i 2021-02-13 20:09

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 g

相关标签:
4条回答
  • 2021-02-13 20:47

    Its a warning but as you have compiled with -Wall -Werror all warnings are treated as error Rest you can find something in similar question.

    Is there a correct way to avoid warnings when comparing two different enums?

    with regards

    hims

    0 讨论(0)
  • 2021-02-13 20:49

    This isn't a warning because of a standards compliance issue, it's one of those "this doesn't seem right" kind of warnings. If you think of the typical uses of enums, doing such a comparison doesn't make much sense in many cases. For example:

    enum Day {
      Sunday,
      Monday,
      Tuesday,
      Wednesday,
      Thursday,
      Friday,
      Saturday
    };
    
    enum Month {
      January,
      February,
      March,
      April,
      May,
      June,
      July,
      August,
      September,
      October,
      November,
      December
    };
    
    enum Day day = Wednesday;
    enum Month month = April; 
    
    if (day == month) { ... }
    

    This evaluates to true, but in general the comparison wouldn't make much sense. If you know you meant it, the typecast will convince the compiler, as you noted.

    0 讨论(0)
  • 2021-02-13 21:04

    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.

    0 讨论(0)
  • 2021-02-13 21:08

    It's warning you because you have the warning flag on. The flag description doesn't explain why it exists, but it's probably safe to assume that it exists to prevent accidental comparisons between different enumeration types, because this usually is an error.

    Furthermore, you are correct that you can use enumeration values the same as you can int constants. And if you said if (myf == c) then it most likely wouldn't have thrown a warning (I say most likely because I haven't experimented, and GCC honestly can do whatever it wants with that warning, but technically c is just an integral constant and does not carry the type enum second). But instead you're explicitly comparing two values of different enumeration types.

    0 讨论(0)
提交回复
热议问题