如何使gcc警告关于将错误的枚举传递给一个函数 [英] How to make gcc warn about passing wrong enum to a function

查看:126
本文介绍了如何使gcc警告关于将错误的枚举传递给一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gcc似乎没有使用以下代码发出警告。如何获得警告?

  typedef枚举
{
REG8_A,
REG8_B,
REG8_C
} REG8;

typedef枚举
{
REG16_A,
REG16_B,
REG16_C
} REG16;

void function(REG8 reg8)
{

}

int main(void)
{
函数(REG16_A); //应该警告错误的枚举
}


解决方案

这种行为的原因是您正在使用C编译器而不是C ++。而在C 枚举类型并不是真正的类型,枚举在C只是保持int常量,他们可以自由地与任何整数和任何算术混合。



在C ++中,你有真正的枚举,而您需要考虑的则是根据语言标准进行的所需的类型检查。



您的问题可以通过两种方式解决:




  • 使用C ++编译器。


  • 将您的代码更改为纯C样式,即不使用枚举,如C中,它们只是常量集,编译器只能帮助您排序常量值。而在C 中,您将负责保持传递常数的类型一致。再次:对于C,枚举成员只是int常量,你不能打字。







  #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 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
}

解决方案

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.

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:

  • Use C++ compiler.

    This way you will have real enums, as you want them.

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆