Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
1  
4  
If you want to get really confused, add endianness in the game. –  mouviciel Jun 28 '13 at 20:23
    
@mouviciel I absolutely HATE whoever damned well ever made endianness a variable...THAT PERSON SHOULD BURN AND DIE –  Jimmy Hoffa Jun 28 '13 at 22:09
    
IBM's page on Declaring and Using Bit Fields in Structures is a bit more explicit in explaining alignment and padding. –  JustinC Jun 29 '13 at 2:42
    
Think of them as a hint to the compiler. Different compilers are free to do what they want with that hint. That way, you wont make invalid assumptions –  mattnz Jun 29 '13 at 3:51

2 Answers 2

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.

share|improve this answer
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

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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