Subject: Re: Bitfields and kernel
To: NetBSD Kernel Technical Discussion List <firstname.lastname@example.org>
From: Matthias Buelow <email@example.com>
Date: 09/29/1999 06:48:57
Greg A. Woods wrote:
>> 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.
I agree that the bitfield notation is probably less error prone
than the bit manipulation idioms but the fact that bitfields are
"highly nonportable" [see below] make their use somehow inappropriate,
especially in kernel code (were bit manipulation is often used on
hardware register values).
>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
Yeah, I have the book open on my lap. On page 183 it says,
"Don't use C or C++ bitfields; they are highly nonportable and tend
to generate voluminous and inefficient code". This is under the chapter
"Space Efficiency" however.
They get even clearer on page 195 in the section on portability:
"Bitfields. Bitfields are so machine-dependent that no one should use
The kernel is nothing highly portable per se (they were discussing
userland programs of course) and the space wasted may be little but
the programmer should be aware of possible pitfalls when using bitfields.
(S)he's got to weigh possible maintainance headache with bitfields,
where (s)he basically doesn't see what the compiler does (except if
(s)he disassembles it) against programmer mistakes which lay open
readable in the source.
The inefficiency mentioned might not be a big deal today but then again
I also run NetBSD on a oldish VAXstation and it is so horribly slow,
every instruction that gets spared counts, especially in often executed
loops (polled-i/o devices for example; dunno if the VAX port does much bit-
juggling in there, though but pio certainly eats a lot of cpu (I pray
that the VAX gurus come up with dma support for the scsi controller fast :)).
>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.]
Yeah, the book is good. I can only recommend it.
> - 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! ;-)