Playing with the code presented in this question, I observed an increase in size of a struct when an 8 bit wide enum is used instead of an uint8_t type.
Please see these code examples:
Code Option A
typedef enum { A, B, C, MAX = 0xFF } my_enum;
struct my_compact_struct_option_a
{
my_enum field1 : 8; // limiting enum size to 8 bits
uint8_t second_element[6];
uint16_t third_element;
};
The offset of the second variable in this struct second_element
is 1. This indicates that the enum field1
is limited to the size uint8_t. However, the size of the struct is 12 bytes. That's unexpected for me.
Compare this to
Code Option B
typedef uint8_t my_type;
struct my_compact_struct_option_b
{
my_type field1;
uint8_t second_element[6];
uint16_t third_element;
};
Here, offset of second_element
is also 1, however, the size of this struct is 10 bytes. That's expected.
Why is the struct in the first code example increased to 12 bytes?
You can always try this code for yourself.