bitfields considered harmful?

Wayne Schlitt wayne at dsndata.uucp
Sun May 7 04:16:40 AEST 1989


In article <705 at cf-cm.UUCP> sme at computing-maths.cardiff.ac.uk (Simon Elliott) writes:
>In article <1473 at uwbull.uwbln.UUCP>, ckl at uwbln.UUCP (Christoph Kuenkel) writes:
>> We have some software using C bitfields like in
>> 
>> [deleted] 
>> 
>> 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.

>Well, you may be right about readability, but I don't think you'll find that
>you've saved much space in your program.  Oh, you might save it in the
>source, but the same shifting and masking is going on under the hood.

>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.  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.

you are correct.  using bit fields and floats (instead of doubles)
will often _cost_ you more space than you save.  it will usually also
slow down your program a great deal.

as a rule of thumb, i figure that every reference to an int variable
will cost you about 2-6 bytes of code, but references to bit fields
will cost you 4-20 bytes code.  references to floats are often as bad,
if not worse since the often require a subroutine call.  the only way
you can end up saving space is if you use the bit fields or floats in
a very large array.



-wayne



More information about the Comp.lang.c mailing list