[NOTE: this is related to Specifying size of enum type in C and What is the size of an enum in C?, but in those questions, the issue was how to minimize the size of the enclosing struct. Here, we want to specify the size of the individual members of the struct, but still get the documentation advantage of typedef'd enums]
I'm implementing the client side of a serial communication protocol. I'd like to use C structs to capture the format of a serial packet, and I'd like to use C enums to define the legal values of the various slots in the packet.
I don't see a way to do both, but since I'm using GCC, it may be possible.
As a hypothetical example of the problem, assume the packet I receive looks like this:
typedef struct {
uint16_t appliance_type;
uint8_t voltage;
uint16_t crc;
} __attribute__((__packed__)) appliance_t;
That's pretty clear, and I'm pretty sure I'll get a struct that is five bytes long. But it doesn't capture the fact that appliance_type
and voltage
can only take on certain values.
I'd prefer something like this...
typedef enum {
kRefrigerator = 600,
kToaster = 700,
kBlender = 800
} appliance_type_t;
typedef enum {
k120vac = 0,
k240vac = 1,
k12vdc = 2
} voltage_t;
typedef struct {
appliance_type_t appliance_type;
voltage_t voltage;
uint16_t crc;
} appliance_t;
...but there's no way that I know of to specify that appliance_type_t is 16 bits and voltage_t is 8 bits.
Is there a way to have my cake and eat it too?
update:
I need to make it clear that I'm NOT expecting the compiler to enforce the enum'd values as setters for the respective fields! Rather, I find that typedef'd enums are a useful construct for maintainers of the code, since it makes explicit what the intended values are.
Note: As I researched this, I noticed that GCC enums accept __attribute__
specifications, but I'm not sure that helps.