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
  • 1
  • 4
    If you want to get really confused, add endianness in the game.
    – mouviciel
    CommentedJun 28, 2013 at 20:23
  • @mouviciel I absolutely HATE whoever damned well ever made endianness a variable...THAT PERSON SHOULD BURN AND DIECommentedJun 28, 2013 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
    CommentedJun 29, 2013 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
    CommentedJun 29, 2013 at 3:51

2 Answers 2

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
  • 1
    Busy [wire] protocols often like packed packets, too ;)
    – JustinC
    CommentedJun 29, 2013 at 2:35
  • I often use bit fields, but then have tests that confirm my presumption about how the compiler is handling it.
    – mattnz
    CommentedJun 30, 2013 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.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.