This is the third post of my Bit fields series; describing how to not use bit fields, how to use them, the limitations imposed by architecture and the compiler’s implementation, the use of volatile, and finally a show-stopper as well as a proposal to fix it.
K&R’s original specification
Kernighan and Richie realised when they described
struct bit fields that they were a “poor man’s” variable: there were otherwise standard operations that you simply could not perform with them because (most) architectures wouldn’t support them.
Unlike a “whole” field in a
struct, a bit field was not necessarily on an address boundary, so a pointer cannot point to one. Therefore, isolated bit fields also couldn’t be passed by reference for manipulation elsewhere. Pass by value of course is straightforward.
Also not allowed are arrays of bit fields. Again, there can be an array of
struct bit fields, but not of the individual fields. For example, the CDR example couldn’t have been written as an array of four two-bit fields. You can imagine how useful it would be if there were four UARTs, to access the
nth UART’s clock field. Alas…
Unlike “whole” fields in a
struct, individual bit fields can’t be declared
static to define a single instance thereof. The whole
struct bit field of course can be
static—just not a single bit field.
But as well as the above architectural limitations, K&R also described how the compiler should (or more correctly, could) implement
struct bit fields.
Comments are welcome. I suggest that generic comments on the whole “Bit fields” series and concepts go on the main page, while comments specific to this sub-page are written here.