C bitfields guarantees

Walter Bright newshound2 at digitalmars.com
Wed Jul 10 07:44:27 UTC 2024


On 7/9/2024 5:44 PM, Timon Gehr wrote:
> On 7/9/24 02:29, Walter Bright wrote:
>>
>> 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"?
> 
> It won't, some edits will be necessary.

Yes, we know it is imperfect. The fewer nits, the better.


>> 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.
> As far as I am concerned, this is an irrelevant straw man. I don't want this. I 
> never suggested anything that would cause this. It's pure FUD.

Having a D code with the same declarations as C code, but the code generated is 
different, is going to lead to subtle memory bugs. I.e. just another footgun.


> It's not nice to hand out a footgun disguised as candy.

Requiring an extern(C) to make it compatible with a C layout is just another 
footgun, and there's no way for the compiler to detect it.

The implementation-defined C layout has been there for what, 50 years? If it was 
so awful there'd be proposals to the C Standard to change it. People gripe about 
it now and then, but just go and fix their code and move on. Neither has C++ 
ever made any effort to change it, even though C++ has `extern "C"`.

I do not understand why this is such a problem, since C compilers change the 
struct member layout based on compiler switches (which I showed in another 
post), and elicits no complaint from anybody.

Having the default D struct member layout not line up with the associated C 
compiler layout is a memory safety issue. Not lining up with an externally 
imposed layout is not a memory safety issue.

The bottom line, whether D supports bitfields or not, whether extern(C) is 
applied or not, to conform to an externally specified layout, you're going to 
have to check and see if it matches. If it doesn't match, there are really 
simple ways to get it to match.



More information about the Digitalmars-d mailing list