How to make gcc warn about passing wrong enum to a function

前端 未结 6 675
失恋的感觉
失恋的感觉 2020-11-29 10:14

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


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 10:43

    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
    

提交回复
热议问题