5 ms·
why not struct Foo{ bool some_flag : 1; bool other_flag : 1; .... } ?
by 12thwonder 5y ago
why not
struct Foo{
bool some_flag : 1;
bool other_flag : 1;
....
}
?
- MontyCarloHall 5y agoBecause a struct of bools != a bitfield. C booleans as defined in stdbool.h are just convenience macros aliasing "true" to 8 bit integer 1 and "false" to 0. AFAIK, there aren't any compilers smart enough to implicitly pack a struct of bools into a bitfield, and then make member access operations implicitly mask the bitfield. Here's a quick example, using the latest GCC: https://godbolt.org/z/c7T54jzGT https://godbolt.org/z/c7T54jzGT
- coolreader18 5y agoNot sure if they edited the comment after you commented, but that is a bitfield now, at least
- MontyCarloHall 5y agoYou're right, I didn't see the :1's. Maybe it was edited, maybe I was just blind?
- deleted 5y ago[deleted]
- isidor3 5y agoI wrote a little solver for some programming puzzle. Thought I was being clever by using bitfields for an array of booleans to reduce memory usage and bandwidth, as they seemed a natural fit for the problem I was solving. Turned out that it was actually significantly faster to use one byte per boolean and forgo the masking operations. I assume the processor was just good enough at keeping its cache filled in that particular workload, so the additional masking operations just slowed things down. So I understand why you might not want a compiler to automatically do this.