Subject: Re: Bitfields and kernel
To: None <>
From: Greg A. Woods <>
List: tech-kern
Date: 09/28/1999 23:40:17
[ On Tuesday, September 28, 1999 at 21:17:57 (+0200), m. k. buelow wrote: ]
> Subject: Re: Bitfields and kernel
> IMHO, implementing binary flags is best done with constants and
> the common C idioms of setting or clearing bits.

I would beg to differ, especially when 

99.9% of all the logic bugs I've ever written had to do with such idioms
and most of them would never have happened if I'd used bitfields and
simpler logic tests.

> It might
> also be considered good style to define constants with enum in
> ANSI C instead of #defining them with the preprocessor because
> why should the preprocessor do something that the compiler itself
> can do as well if not better.

Yes, absolutely.

Since my advice might be seen as suspect [:-)], I would strongly advise
that folks interested in good C programming constructs take a long hard
read of Kernighan & Pike's new book "The Practice of Programming".  I
think you'll find it corroberates what I say rather well.  In fact I've
not yet found anything in it that I would want to strongly disagree
with!  [I was overjoyed to find it on the reading list for what seems to
be a core comp-sci course at the UofToronto this fall.]

Quick summary:

	- bitfields are in fact much easier to understand and maintain
          than using binary logic idioms and they should be used
          wherever a group of related logic flags are desired in an
          internal data structure.

	- yes, enums can be "better" than #define's for magic numbers

	- neither structures nor bitfields should ever be contemplated
          when trying to map meaning onto external data, especially in
          any program that might ever even possibly be run more than
          once, and especially if it might ever be re-compiled!  ;-)

I agree that there are times when bitfields might cause more
instructions to be generated on a number of platforms (though perhaps
this is really just a compiler/optimiser deficiency? ;-), but I don't
think Kuth's rule of thumb can be ignored: "Premature optimisation is
the root of all evil (or at least most of it) in programming."

							Greg A. Woods

+1 416 218-0098      VE3TCP      <>      <robohack!woods>
Planix, Inc. <>; Secrets of the Weird <>