3 ms·
The solution is just to make sure you have padding fields that result in an overall size that's a multiple of however many bits e.g. 32 or 64 bits. Use static_a
by eecsninja 8y ago
The solution is just to make sure you have padding fields that result in an overall size that's a multiple of however many bits e.g. 32 or 64 bits. Use static_assert() to enforce the size.
See my earlier comment about unit testing too.
- jcranmer 8y agoWell, to have a good chance of avoiding the landmines, you need to: * Pack the bitfields in a struct all by themselves. Don't mix bitfields and non-bitfields in the same struct. (This means that you limit the scope of insanity to other bitfields, not potentially expanding it to other regular fields). * Make sure that the underlying type of all the bitfields within the struct have the same type. And make it be unsigned. * Pad the bitfields to the appropriate size of the type. * Only access the bitfields by copying them to/from the appropriate local variable (you don't want to trip code up on the bitfields-aren't-quite-the-type-they-say-they-are logic).
- eecsninja 8y agoI've only used bitfields for register access. I get the first 3 points you make. (I use uint32_t for all fields) What is the danger in #4 if you've followed #1-3? You seem overly paranoid. Is there something from your experience that makes you nervous about bitfields?
- jcranmer 8y agoI work on compilers for a living, which means I have a first-hand impression of the fallout of "the semantics seem clear until you actually think about all of the corner cases." I also have an appreciation for compilers blindly doing the wrong thing when you start mixing weird constructs together, and bitfields are very much a weird construct. The last rule is a recognition that bitfields are weird constructs, and their interactions with other weird constructs are likely to cause problems. One example: try using a bitfield in a ternary lvalue operation, especially with clang.