bitfields considered harmful?

Doug Gwyn gwyn at smoke.BRL.MIL
Sat Apr 29 12:23:12 AEST 1989


In article <1473 at uwbull.uwbln.UUCP> ckl at uwbln.UUCP (Christoph Kuenkel) writes:
>During various ports of that to different SysV machines (should i have posted
>that to comp.unix.wizards?) we ran into problems because of compiler bugs.
>One time, assembler code was produced that tried to shift a word 0 bits to
>the right (68020), another time bitfields read nonzero all the time ...

Yes, I find that people are frequently surprised when I point out that
some machines' shift instructions malfunction if you try to use them to
shift by 0 bit positions.  The proposed C standard allows undefined
behavior for << and >> by negative of too-large amounts, but it requires
shifting by 0 to work.  This means that some implementations are going
to have to generate code to test for a 0 shift count and take different
actions in such a case, unless the compiler is able to determine that it
cannot occur.

>Now, are bitfields generally considered harmfull?  Are there other good
>reasons to avoid them?

The main reason to avoid them is because so many compilers get them wrong.

>what does ANSI C say about it?

Bit-field support is required of a conforming implementation.  Their
properties are left fairly implementation-defined, but not so much so
that the bugs you mentioned are permitted!

>I like them cause they save space and are much more readable than 
>oriing/anding with # defines and i dont have to bother with questions like
>how many flags fit into one int.

Those are good reasons to prefer bit fields.

Sometimes one sees bit fields being used to match externally-imposed
storage layout formats.  This is NOT a good use of bit fields, because
they are not tightly enough constrained to guarantee such detailed
matching.  The compiler could even change its allocation of bit fields
between releases, although it might cause customer complaints if it did.



More information about the Comp.lang.c mailing list