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
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.)