When you tell the C compiler this:
int bit1 : 1
It interprets it as, and allocates to it, an integer; but refers to it's first bit as bit1
.
So if we consider your code:
struct value
{
int bit1 : 1;
int bit2 : 4;
int bit3 : 4;
} bit;
What you are telling the compiler is this: Take necessary number of the int
s, and refer to the chunks bit 1 as bit1
, then refer to bits 2 - 5 as bit2
, and then refer to bits 6 - 9 as bit3
.
Since the complete number of bits required are 9, and an int
is 32 bits (in your computer's architecture), memory space of only 1 int
is required. Thus you get the size as 4 (bytes).
Instead, if you were to define the struct
using char
s, since char
is 8 bits, the compiler would allocate the memory space of two char
s for each struct value
. And you will get 2 (bytes) as your output.