4 ms·
The bit-field feature of C structs is underutilized. People are still writing hex constants and using AND and OR to clear and set bits. Let the compiler do tha
by Animats 10y ago
The bit-field feature of C structs is underutilized. People are still writing hex constants and using AND and OR to clear and set bits. Let the compiler do that; it's more readable. As of C99, there's named structure initialization, which makes bitfield constants more readable.
- stephencanon 10y agoC11 §6.7.2.1: "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified." This makes bitfields quite difficult to use correctly when portability is of interest. It's often easier to write a couple inline get/set functions and use bit indices. If portability isn't a concern, then sure, have at it.
- Animats 10y agoThat's an escape clause for endian issues. If you write hex constants, you still have endian issues.
- tedunangst 10y agoVery annoying when you want to pass the flags field to a function, however.
- Animats 10y agoRight, because a structure initializer in C is not a first-class object. You can't use it in an expression.
- Too 10y agoIf your struct is mapped to a register then writing two bit fields in sequence will trigger two separate writes on the hardware register when you intended to write both the bits in one shot.