简体   繁体   中英

How to warn when assigning or performing arithmetic with different enum types in GCC?

While I'm aware this is valid C not to differentiate between enum types.

GCC does have -Wenum-compare (which I'm using) and works as expected.

I tried using -Wconversion but this doesn't make any difference.

How can assignments and arithmetic operators ( + / - / & / | ... etc) also generate warnings? (assignment, or and... etc)

{
    enum Foo f = SOME_VALUE;
    enum Bar b = SOME_OTHER_VALUE;

    if (f != b) {
        /* this warns! */
    }

    f = b;  /* <-- how to warn about this? */
    f |= b;  /* .. and this? */

}

Notes:

  • Switching to C++ is not an option (as suggested in other answers) .
  • This question is closely related, however its not a duplicate because it's about passing arguments instead of arithmetic.

According to this answer , only clang supports the desired behavior.

There are some approaches to emulate strongly typed enums in C, but they seem to have various limitations.

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