4

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.

  • 1
    Busy [wire] protocols often like packed packets, too ;) – JustinC Jun 29 '13 at 2:35
  • I often use bit fields, but then have tests that confirm my presumption about how the compiler is handling it. – mattnz Jun 30 '13 at 21:43
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.