3 ms·
With shifts and masks you know where the bits are. You know where the bits are within a single word. But if you have a struct with multiple fields, it’s not sa
by iainmerrick 5y ago
With shifts and masks you know where the bits are.
You know where the bits are within a single word. But if you have a struct with multiple fields, it’s not safe to rely on the exact memory layout even if it doesn’t have any bitfields.
If you need to represent a very specific memory layout, it’s not just bitfields you need to avoid, it’s structs in general.
Conversely, if you don’t need to guarantee a specific layout, bitfields are fine to use, and could be a useful optimisation hint for the compiler.
- ncmncm 5y agoIn other words, you don't understand.
- iainmerrick 5y agoHere’s an example where I think bitfields are totally appropriate: Say I have a window manager, and I want to attach a bunch of boolean flags to each window object (isVisible, isMaximized, etc). I don’t need to serialize them to disk. It’s highly preferable that they should be efficiently bit-packed, but not strictly essential. The conservative way to implement that would be bit-shifts and masking (either manually or via a macro). But implementing it with bitfields would be a lot easier and less error-prone, and would work just as well. What problems do you see with the bitfield approach?
- ncmncm 5y agoMissing the point, again. If it works on your particular compiler release, on your particular CPU chip stepping, that tells you nothing about the next compiler over and the next chip over. amd64 and arm64, compiled with gcc or clang, you are unlikely to run into these problems. But code tends to get around.
- iainmerrick 5y agoIt sounds like the point you want to make is that the implementation of bitfields is often buggy, therefore you should always avoid using them - does that sound right? If so, I think that’s overly paranoid. The examples that are being given here are baroque usage that would immediately stand out in a code review - memory-mapped registers, conditional lvalues, volatile and atomic fields. The point I wanted to make is that simple straightforward usage of bitfields, like the example I gave, works fine on any platform you’re likely to encounter. There’s plenty of widely-used code out there that uses bitfields. I just did a code search to check that (the particular example I was thinking of comes from iOS) and found some in Clang - funnily enough, in its representation of lvalues!