[Ovmsdev] Bitfields and C Compilers

Tom Saxton tom at idleloop.com
Thu Feb 7 10:33:12 HKT 2013


on 2/6/13 1:55 PM, Michael Balzer wrote:

> thanks for the info... I'll change the bit fields back to #defines, had
> those in the first place but thought bit fields were meant for this kind
> of job.

Bitfields are a nice feature of the language and are intended for exactly
this purpose, at least for runtime structures.

I am opposed to this sort of thing:

car_doors1 |= 0x0c;     // Set charge and pilot bits

Magic numbers are bad, especially when they have hidden maintenance issues.

Language constructs with self-explanatory names are good. Defined constants
with self-explanatory names are almost as good.

For bitfields that define data passed between different programs, equivalent
to a binary file format, which thus have to be identical at the bit level
across different compilers, processors and platforms, defined constants are
probably best. You can make compiler-based bitfields work by using a program
to generate a header file with the bitfields in the right order for that
build's compiler, but that's probably more hassle than is appropriate for
this project.

For bitfields that are for runtime only and not passed between programs,
using the language-defined bitfields is preferable to named constants as
they are easier to maintain.

    Tom





More information about the OvmsDev mailing list