Whenever I read a code like this:
struct node
{
int x : 2;
int p : 4;
}n;
with bit fields involved, I get really confused, as to how they are represented in memory, what is sizeof(n)
etc., how does it differ with normal members of structures? I tried referring K&R and http://en.wikipedia.org/wiki/Bit_field but they little to remove my confusion. What concepts of bit fields am I failing to grasp?
5
sizeof reports in units of bytes, so it is not well behaved for bit fields.
C doesn’t have a clear standard how bit fields have to be laid out, and in general, you should be extremely cautious about any assumptions, especially if different platforms or
different compilers may come into play.
I usually use manual packing/unpacking schemes, but hide the details in acessor
functions, in those rare circumstances where packing information into integers
at the level of bits is appropriate. The only case where the layout of bit fields
absolutely does matter is writing drivers for hardware.
2
Correct, whenever a bit field is used, everyone gets confused. Because bit fields are very poorly specified by the standard and can have pretty much any memory layout imaginable.
what is sizeof(n)
Nobody knows, including the C standard committee.
how does it differ with normal members of structures?
Normal structures have well-defined behavior. Apart from the case of struct padding, you can always predict how a normal structure is stored in memory. For bit fields, all bets are off.
Detailed info here.
The solution is to never use bit fields. It is a superfluous and dangerous part of the C language.