For this question, the size of the data types used is:
- char: 1 byte
- unsigned: 4 bytes
- long: 8 bytes
I found this answer which explains the size of structs containing bit fields by going top to bottom and allocating more bytes if necessary. As far as I understand, whether packing the members together or not is implementation defined but if packing is done, this may be a way to do it. So far so good.
How does this work when mixing data types? The size of the struct is apparently 4 bytes.
struct bitfield1
{
char a : 1; // char needs 1 byte, so 1 byte allocated
char b : 1; // this fits inside the first byte allocated
char c : 1; // this fits inside the first byte allocated
unsigned d : 1; // this would fit inside the first byte allocated, but it allocates 3 bytes more?!
};
I would have said that it either just fits inside the first byte or allocates 4 more bytes because it is an unsigned integer.
Similarly, when mixing more data types...
struct bitfield2
{
char a : 1; // char needs 1 byte, so 1 byte allocated
unsigned b : 1; // this fits inside the first byte allocated
char c : 1; // this fits inside the first byte allocated
long d : 1; // this would fit inside the first byte allocated, but it allocates 7 bytes more?!
};
...it allocates 8 bytes in total, the size of long. How does this work in detail?