如何让 gcc 警告将错误的枚举传递给函数 [英] How to make gcc warn about passing wrong enum to a function
问题描述
gcc 似乎没有用以下代码产生警告.我怎样才能让它产生警告?
gcc doesn't seem to produce a warning with the following code. How can I get it to produce a warning?
typedef enum
{
REG8_A,
REG8_B,
REG8_C
}REG8;
typedef enum
{
REG16_A,
REG16_B,
REG16_C
}REG16;
void function(REG8 reg8)
{
}
int main(void)
{
function(REG16_A); // Should warn about wrong enum
}
推荐答案
这种行为的原因是您使用的是 C 编译器而不是 C++.并且 在 C 中 枚举类型并不是真正的类型,C 中的枚举仅包含 int 常量和它们可以与任何整数和任何算术自由混合.
The reason of such behaviour is that you are using C compiler rather than C++. And in C enum types are not really types, enums in C just hold int constants and they can be freely mixed with whatever integers and whatever arithmetic.
在 C++ 中,您有真正的枚举,正如您所想的那样,并且按照语言标准的规定进行所需的类型检查.
In C++ instead you have real enums as you would like to think of them, and the needed typechecking occurs as conveyed by the language standard.
您的问题可以通过两种方式解决:
Your problem can be resolved in two ways:
使用 C++ 编译器.
Use C++ compiler.
通过这种方式,您将拥有真正的枚举,如您所愿.
This way you will have real enums, as you want them.
将您的代码更改为纯 C 风格,即不使用枚举,因为在 C 中它们只是常量集,编译器仅帮助您对常量值进行排序.而在 C 中,you 将负责保持类型"传递的常量一致.再说一次:对于 C,枚举成员只是 int 常量,你不能让它们输入.
Change your code to be in pure-C style, i.e. not using enums, as in C they are merely constant sets where the compiler only helps you to order the constant values. And in C you will be the one responsible to keep the "types" of passed constants consistent. Once again: for C, enum members are just int constants, you can't make them typed.
#define REG8_A 0
#define REG8_B 1
#define REG8_C 2
#define REG16_A 0
#define REG16_B 1
#define REG16_C 2
这篇关于如何让 gcc 警告将错误的枚举传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!