Is there a way to get the compiler to warn if an integer is outside the 'range' of an enum
? For example, something like this:
enum Brothers {Snee, Snoo, Snum};
int main(void) {
enum Brothers k;
k = Snee;
k = 9; // compiler warning for an int outside [0,2] ?
}
I couldn't find an option on GCC matching exactly what you want. There are some enum-related compiler flags for GCC that will make enums slightly more behaved. For example, -Wenum-compare
will give a warning when comparing enums of different types for equality:
enum fruit {
APPLE,
BANANA
};
enum colors {
RED,
BLUE
};
if (APPLE == RED) { // -Wenum-compare gives compiler warning here.
...
}
The option you're looking for does seem to exist on clang though as -Wassign-enum
.
Not for gcc as of version 10.2. There's a related open enhancement request from 2002 but developers haven't seemed interested in implementing it.
clang will warn about this if given the -Wassign-enum
option: https://godbolt.org/z/zv8an5
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.