简体   繁体   English

将 integer 分配给枚举时如何收到警告?

[英]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?在将普通 integer 分配给枚举类型的变量时,有没有办法让 Clang 或 GCC 发出警告? This question refers to C, not C++.这个问题是指 C,而不是 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". “经典”英特尔编译器针对这些情况发出警告:警告 #188,“枚举类型与另一种类型混合”。 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.但是,这是一个由志愿者运行的开源项目,我们无法定期使用这个非免费编译器进行测试,也无法将其集成到 CI 管道中。 Having seen the value of these checks, I am wondering if there is a way to get them with Clang or GCC.看到这些检查的价值后,我想知道是否有办法使用 Clang 或 GCC 获得它们。

Checking the GCC warning documentation shows no options that would do as you request.检查GCC 警告文档显示没有可以按照您的要求执行的选项。

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 ).switch语句( -Wswitch-Wswitch-enum )中缺少枚举值的选项,不同枚举类型的值之间的比较( -Wenum-compare )以及不同枚举类型之间的转换( -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:编译器开发人员可能已经感觉到关于将int值分配给枚举类型的左值的警告将没有用,因为它会警告普通的期望分配,例如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 .其中, i+1int因为1int并且+的操作数被转换为普通类型,然后将此int分配给enum weather i

There are some kludges to use enumerations with some type safety . 使用具有某种类型安全性的枚举存在一些问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM