C bitfields guarantees

Walter Bright newshound2 at digitalmars.com
Tue Jul 9 00:29:20 UTC 2024


On 7/7/2024 8:49 AM, Steven Schveighoffer wrote:
> Simple, no. Predictable, yes (it's unambiguous). And not obvious.

It is trivially obvious to the most casual observer!

Joking aside, it's the same technique used to inure a struct layout against 
member alignment issues.


> What I want is 
> for the compiler to *require* you to do this to avoid inconsistencies. It is 
> going to be a mystery to anyone reading it *why* they put these things in there.

I've seen fields named "pad" or "padding" many times in C code. It's normal 
practice. Failing that, the purpose of comments is to add the 'why'. One could 
also use `static assert` for extra insurance.

I've also seen fields named "reserved". No comment needed.


> To give some examples, we require empty if statements to use {} and not ;. It 
> doesn't require any new syntax but it helps you avoid issues that many people 
> make, even though it is allowed in C.

Then one could not write a C compatible bitfield.


> We require explicit conversion when narrowing the range of an integer (i.e. 
> assigning a long to an int). This avoids issues that many people would make, 
> even though it is allowed in C.

The C semantics are still allowed by adding a cast.

Let's say Bob (poor Bob) needs to convert 20,000 lines of C code to D. I know 
you've done some of this yourself! Bob doesn't want to go through it line by 
line. Isn't it nice for Bob if it "just works"? If all those data declarations 
just work? Especially if the result still has to be compatible with the files 
that C code wrote out?

But what if the compiler says "Bob, you can't lay out a bitfield like that!" Or 
worse, it lays out the bitfield into a portable (but different) layout. Then it 
doesn't just work, Bob has got some debugging to do (while Bob curses D and me), 
and Bob's got to figure out an alternative. Who wants to do that? Not Bob. Not 
me. Not nobody not nohow.


>> There are many existing ways to accomplish this. Adding more language features 
>> to duplicate existing capability needs a very strong case.
> I'm not asking for any new features.

Every switch that changes the semantics is a new feature and a new source of 
complexity and bugs.

One of my original requirements for D was no switches that change language 
semantics. I have failed at that. But I wasn't wrong to aspire towards it.



More information about the Digitalmars-d mailing list