2

Is there a way to get Clang or GCC to warn when assigning a plain integer to a variable of enum type? This question refers to C, not C++.

Example:

typedef enum foo_e { A=1, B=2 } foo_t;

foo_t fun() {
    foo_t x = A; // this is fine
    foo_t y = 2; // should trigger a warning
    int z = B;   // this is fine
    return 1;    // should trigger a warning, as the return type is foo_t
}

The "classic" Intel compiler issues a warning for these cases: warning #188, "enumerated type mixed with another type". This revealed several real bugs in our code. However, this being an open-source project run by volunteers, we do not have the possibility to test with this non-free compiler on a regular basis, and cannot integrate it into CI pipeline. Having seen the value of these checks, I am wondering if there is a way to get them with Clang or GCC.

Szabolcs
  • 24,728
  • 9
  • 85
  • 174
  • That's not invalid. Enumerations and enumeration constants are really basically just plain integers. Actually it's quite common to use enumerations as bitwise flags, and use bitwise OR (`|`) to construct masks or bitsets, and then assign to a variable of the enumeration type. – Some programmer dude Aug 13 '22 at 07:45
  • 1
    @Someprogrammerdude No, it's not invalid. That does not mean that getting a diagnostic for this is not useful. – Szabolcs Aug 13 '22 at 08:05
  • 1
    @Szabolcs "enumerated type mixed with another type" looks like a C++ compiler warning. In C, `foo_t` is not a new type. "should trigger a warning" is incorrect for C. – chux - Reinstate Monica Aug 13 '22 at 10:31
  • 1
    @chux-ReinstateMonica: So there is a solution. Write that portion of the code so it can be compiled as C/C++. Compile as C++ to check for warnings. Compile as C for actual use in the program. – Eric Postpischil Aug 13 '22 at 10:32
  • @EricPostpischil Interesting approach. – chux - Reinstate Monica Aug 13 '22 at 10:34

1 Answers1

2

Checking the GCC warning documentation shows no options that would do as you request.

There are options for missing enumeration values in switch statements (-Wswitch and -Wswitch-enum), comparisons between values of different enumeration types (-Wenum-compare), and conversions between different enumeration types (-Wenum-conversion).

Likely the compiler developers have felt that warnings about assigning int values to an lvalue of enumeration type will not be useful because it will warn about ordinary desired assignments such as i = i+1 in:

for (enum weather i = sunny; i <= rain; i = i+1)
    …

In that, i+1 is an int because 1 is an int and the operands of + are converted to a common type, and then this int is assigned to the enum weather i.

There are some kludges to use enumerations with some type safety.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312