简体   繁体   中英

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 a number of 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.

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 .

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