Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a warning when assigning integer to enum?

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.

like image 758
Szabolcs Avatar asked Oct 23 '25 00:10

Szabolcs


1 Answers

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 typically int (because 1 is an int and the operands of + are converted to a common type) or unsigned int (because the compiler may use this as an underlying type for the enumeration), and then this int or unsigned int is assigned to the enum weather i.

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

like image 164
Eric Postpischil Avatar answered Oct 25 '25 02:10

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!