Iain McDonald

Specify size of enum?

Discussion created by Iain McDonald on Sep 30, 2010
Latest reply on Oct 27, 2011 by bigmac

I'm using codewarrior 10 for the MC9S08SH8. I've got a union producing an issue which took a while to track down, and stems from the size of an enum. The size of an enum is compiler-specific and should default to the smallest integral type which is large enough to fit all of the values, but not larger than int. In this case, it seems the sizeof enum is fixed at 16-bit. For starters, that wastes a heck of a lot of memory if you use a boolean typedef (which I do). The real problem was caused by this code:


typedef enum { SOME_COMMAND=0x00, ...        SOME_OTHER_COMMAND=0x0F } Commandt;typedef union{ UINT8 s[4]; struct {
                Commandt command;  UINT16 address;  UINT8 data; } l;} Packet;

 I expected this to allow me to write the raw bytes and then efficiently access the contents, but of course the CMD_Commandt overlapped the high byte of the address and broke the code. I've managed to correct the issue with the type sizes options in the build settings, but it's not exactly portable code.



Is there a #pragma option to set the size of an enum, or better yet, some way to force it to always use the smallest number of whole bytes for an enum?


I'd really like it to be able to use the smallest number of bits for an enum, and hence stack multiple boolean variables in a bitfield, but I suspect that's a bridge too far :smileyhappy:.