justanotherguy justanotherguy - 1 month ago 6
C Question

Size of bit-field union which has more members than its size

#include <stdio.h>

union mix {
unsigned char a1:1;
unsigned char a2:4;
unsigned char a3:4;
unsigned char a4:1;
unsigned char a5:4;
unsigned char a6:4;
unsigned char a7:1;
unsigned char a8:4;
unsigned char a9:4;
unsigned char a10:1;
unsigned char a11:4;
unsigned char a12:4;
};

int main() {

printf("Sizeof mix = %d bytes\n", sizeof(union mix));

return 0;
}


The output is 1 byte.

What happens to bit-field members which exceed 8 bits ? Apparently I can still set and get correct values for any bit-field member.

UPDATE

Thank you for clearing my confusion. One side question: in what order do the bits get stored in memory ? Assuming it is little endian memory so 0xabcd will be stored in memory as 0xd, 0xc, 0xb, 0xa.


  1. Will m.a1 be part of 0xd OR oxa?

  2. Will it be bit 3 or bit 0 of 0xd(or 0xa)?


cxw cxw
Answer

@tkausl is correct. In a union, each member overlaps with all the other members in memory. Therefore, each field in the bitfield overlaps with the others depending on the number of bits in each field and the endianness of the platform. For example, a1 and a10 probably always have the same value.

Since all the fields are overlapped in memory, you only need as many bytes as are required to hold the longest field. Since one byte will do it, that's the size of the union.

Comments