Jack Klein said:
Up to here, I agree with you...
...but I disagree with this last point. It may be true enough in
general, but there are specific implementations where it is done well
and extremely useful.
This is the case in many embedded microcontroller/DSP implementations
that I have used. It is quite common for the silicon vendor to supply
extensive header files defining all of the on-chip memory mapped
peripherals with unions overlaying bit fields and unsigned integer
types.
Of course, they make sure the bit ordering and other features of their
definitions compile properly with their compiler. They would not
necessarily be portable to any other compiler, but then neither would
the hardware peripherals they address.
Actually, it seems in your last paragraph that you are agreeing with Chris.
Of course, they make sure the bit ordering and other features of their
definitions compile properly with their compiler. They would not
necessarily be portable to any other compiler ...
But they _would_ be portable to any other compiler, if they:
There is definite room for improvement with 'C'. Not only is there the
portability issue, but there is a learning and training cost. I've worked
with compilers that pack bitfields MSB first and LSB first, and when I look
at memory dumps and so on I need to refamiliarize myself with how the
compiler packs each time ... it would be easier if they all packed the same
way.
And I also wish there were a way to give the compiler _MORE_ freedom in what
it did in some cases. When one has bitfields that are being used for
compact storage only (and not for ill-advised type conversions and so on),
one should be able to tell the compiler to rearrange fields as it pleases.
Two examples come to mind:
a)A processor I've used in the past had a neat instruction for swapping
nibbles of a byte. The compiler did a really good job if one just happened
to place a bitfield of size 4 as the upper nibble ... the compiler should
have the freedom in some cases for force this alignment by rearranging
bitfields.
b)In general, shifting and masking to extract bitfields is an expensive
operation (for embedded systems). The compiler should have the freedom in
some cases to align frequently-used bitfields against the LSB to eliminate
the shifting.
The *enough* is a problem. One should be able to give the compiler less
freedom in some cases and more freedom in others.