DIP: add Bit Fields

Walter Bright newshound2 at digitalmars.com
Thu Mar 7 19:42:36 UTC 2024


On 3/7/2024 4:04 AM, Dennis wrote:
> On Thursday, 7 March 2024 at 04:26:56 UTC, Walter Bright wrote:
>> https://github.com/WalterBright/documents/blob/master/bitfields.md
> 
>> I've seen plentiful use of it, and have not seen any "do not use bitfields" 
>> programming guidelines.
> 
> [Bit-fields in C have acquired a poor reputation in the programming 
> community](https://andrewkelley.me/post/a-better-way-to-implement-bit-fields.html)

All Zig is doing is providing a slightly different syntax that does the same 
thing as C. Zig is layering on a magic "pointer to bit field type" that I 
attempted to implement in D long ago, but it has too many special cases and 
turned out to be unworkable. You cannot convert a pointer to bit 3 to a void*, 
making the special bit pointer type rather useless.


> [C bitfields considered 
> harmful](https://www.flamingspork.com/blog/2014/11/14/c-bitfields-considered-harmful/)

I don't know of any C compiler that puts a single bit flag in a 64 bit int. He 
didn't show enough code to see the source of his problem. I suspect he doesn't 
know what he's doing.


> [So don't go for bitfields "just 
> because"](https://yarchive.net/comp/linux/bitfields.html)

Linus suggests using explicit bit masks instead.


> [Bitfields seem to be perfect for this, but they're so poorly specified in the 
> standard that common "best practice" is to avoid 
> them.](https://www.reddit.com/r/C_Programming/comments/146tbnp/why_is_using_bitfields_in_high_performance/)

I.e. the layout is implementation-defined. That's correct. But in reality, it is 
fixed. There is no way that gcc on Linux is *ever* going to change the bit field 
layout, because it would break legions of existing code. It is cast in concrete, 
and is as immutable as it gets. The same for Microsoft C.

Furthermore, if you use `int` as the base type for bit fields, the layouts are 
all the same in all the C compilers I've encountered. For practical purposes, it 
is defined.

If you are still concerned about the layout, like you want a portable file 
format, don't use bit fields. Use std.bitmanip.

But if you want to be compatible with C code that uses bit fields, the builtin 
bit fields are the way to go.

If you like a nice syntax, bit fields cannot be beat.

If you want to pack data in your structs and use less memory for your program, 
bit fields are again a winner. DMD uses far too much memory. Much of the data 
structs it uses can be packed, but since without bit fields the syntax is just 
too ugly, there's been little effort to do that. Convenience is everything.

If you still don't like bit fields, don't use them.

And yes, you can't do volatile, shared, atomic, or pointers to bit fields. You 
can't do those with std.bitmanip, either. Nor can you do them with manual 
masking and shifting.


More information about the dip.development mailing list