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

前端 未结 6 684
失恋的感觉
失恋的感觉 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:37

    The only way I can see of generating a warning is if you are prepared to pass pointers rather than bare enums, e.g.

    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)
    {
        REG16 r = REG16_A;
        function(&r);
        return 0;
    }
    

    Not exactly an elegant solution, but it does give a warning, at least with gcc -Wall:

    $ gcc -Wall warn_enum.c -o warn_enum
    warn_enum.c: In function ‘main’:
    warn_enum.c:23: warning: passing argument 1 of ‘function’ from incompatible pointer type
    $
    

提交回复
热议问题