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

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

    As others have pointed out, C does not differentiate between an enumerated type and the underlying integer type. (Some compilers might include type-checking for enums or typedefs as extensions; YMMV.)

    To get type-checking in C, you can use structs, but then you lose use of the built-in comparison operators and the ability to switch on a variable. You might try something like this, though:

    typedef struct {
        enum {
            reg8_val_A,
            reg8_val_B,
            reg8_val_C,
        } val;
    } reg8;
    #define reg8_A (reg8){.val = reg8_val_A}
    #define reg8_B (reg8){.val = reg8_val_B}
    #define reg8_C (reg8){.val = reg8_val_C}
    …
    bool
    is_A_or_B(reg8 reg) {
        if reg.val == reg8_A.val    // one way to compare
            return true;
        switch (reg.val) {
            case reg8_val_B:        // the other way to compare; note that
                return true;        // “case reg8_B.val:” will *not* work
            case reg8_val_C:
                return false;
            default:
                fprintf(stderr, "bad reg value %d\n", reg.val);
                abort();
        }
    }
    

    (Uses some C99 features.)

提交回复
热议问题