bitfields considered harmful?

Mark A Terribile mat at mole-end.UUCP
Sun May 7 10:44:55 AEST 1989


> > We have some software using C bitfields ... 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.

Also, when you have an existing data layout which is NOT packed, and you have
to pack it, bitfields can save your pretty little butt--assuming that you've
used structs ``like you're supposed to.''

> Well, you may be right about readability, but I don't think ... you've saved
> much space in your program. ... the same shifting and masking is going on ...

> Now to the real question - how much space have you saved by packing the data?
> probably not a lot, unless you are using tens of booleans. ...

If you have several thousand instances of a struct, and if you can store ten
bytes each instead of twenty-eight, you've saved a lot.  Maybe not a lot on a
PC with two megabytes, but a lot for a TSR program or an awful lot in an
embedded system whose price will depend strongly on how much RAM you have to
build into it.

> How much space have you wasted by generating code to shift and mask?
> Depends how often you look at the flag, right?  Whether or not you save
> space is a trade-off, like so many of these religiously-held ideas.  There
> is no universally-right answer.

Remember that memory is not memory.  In an embedded system, there may be
ten or one hundred bytes of ROM available for every byte of RAM.

I worked on such a system; it's one that you've probably seen advertised.
We saved our tender parts by going to bitfields, even though many of our
programmers were not really familiar with them.  We needed to move a unit-
cost/functionality curve by packing the bits, and they were used in so many
places (throughout some three hundred thousand lines of code) that going over
the code just once to make the change would have delayed us past our market
window.  It was, simply put, unthinkable.  (And I did once make a change
that required changing hundreds of uses of one datum through about two
thirds of the system.  Our release librarian at first didn't believe that
one change could touch over two hundred source files.  The alternative to
that one change was a similar number of instances of different changes, so
the developers OK'd it.)

Dennis Ritchie once called bitfields ``a botch and a blemish.''  Are they?
Compared to the rest of C and C++, you bet.  Have they saved their users
millions of dollars?  I can testify that they have.

What the trade-offs are depends on your circumstances.  Aesthetics,
science, and economics are all vital concerns of the Useful Arts of
Engineering.  None of them by itself IS Engineering.
-- 

(This man's opinions are his own.)
>From mole-end				Mark Terribile



More information about the Comp.lang.c mailing list