C bitfields suck…

…and not in a good way.

Not only does the C standard, ISO/IEC 9899:1999 (E), not specify (or allow the programmer to specify) the direction in which bit fields are allocated in a word, it doesn’t specify (or allow the programmer to specify) what size the complete structure should be. The implementation is allowed to introduce any arbitrary amount of padding at the end of the structure.

I wanted to define a bit field specifying how bits are used in a 16-bit data item stored in an array; one bit would be a tag and 15 bits would be data. So I tried:

struct oops_t

{

  unsigned int tag_small_int: 1;

  unsigned int value: 15;

};

What I actually get with GCC on an x86_64 Linux system is a 32-bit structure.  I could live with that, except that I wanted to use the oops_t inside another union with other 16-bit data items.

It’s great that the standard allows some flexibility for implementations.  But given that one of the strong points of C is supposed to be the ability to use it for low-level programming, where the programmer actually cares about things like bit positions, C should have provided a standard way to tell the compiler “I want it done this way.”

Ada got this right with representation specifications back in 1983.  C bitfields are still nearly useless in the 1999 C standard.

This entry was posted in Software. Bookmark the permalink.

2 Responses to C bitfields suck…

  1. Les Hildenbrandt says:

    Could you use sizeof() and conditionals to get a structure that was a constant size. With the compiler I use, an int is 16 bits, so bitfields allways grow to the next 16 bit boundry.

  2. Eric says:

    The structure is constant size: the fields add up to exactly 16 bits. The compiler is adding an additional 16 bits of padding to make it 32 bits, which is allowed by the C standard but not desired in this case.

    Even if there is a workaround for this compiler, I won’t be able to use it because it won’t be portable.

Leave a Reply