[英]Compiler Warn on enum
Is there a way to get the compiler to warn if an integer is outside the 'range' of an enum
?如果 integer 超出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.我在 GCC 上找不到与您想要的完全匹配的选项。 There are some enum-related compiler flags for GCC that will make enums slightly more behaved. GCC有一些与枚举相关的编译器标志,这将使枚举稍微表现得更好。 For example, -Wenum-compare
will give a warning when comparing enums of different types for equality:例如, -Wenum-compare
在比较不同类型的枚举是否相等时会给出警告:
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
.您正在寻找的选项似乎确实存在于clang虽然为-Wassign-enum
。
Not for gcc as of version 10.2.自 10.2 版起不适用于 gcc。 There's a related open enhancement request from 2002 but developers haven't seemed interested in implementing it. 2002 年有一个相关的开放增强请求,但开发人员似乎对实现它并不感兴趣。
clang will warn about this if given the -Wassign-enum
option: https://godbolt.org/z/zv8an5如果给定-Wassign-enum
选项,clang 将对此发出警告: https://godbolt.org/z/zv8an5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.