C bitfields guarantees
Walter Bright
newshound2 at digitalmars.com
Sat Jul 6 23:34:12 UTC 2024
On 7/5/2024 8:23 PM, Steven Schveighoffer wrote:
> My recommendation still is either:
>
> 1. Denote D bitfields by a specified layout system (pick the most common C one
> and do that). C bitfields can match the C compiler.
> 2. Simply forbid problematic alignments at compile time:
>
> ```d
> struct S {
> uint x;
> uint64 a : 24;
> uint64 b : 24;
> uint64 c : 16;
> }
>
> // error, alignment of bitfield `a` may not match C layout, please use padding
> or aligned bitfields to specify intended layout.
>
> // these are OK.
> struct SWithPadding {
> uint x;
> uint _; // padding
> uint64 a : 24;
> uint64 b : 24;
> uint64 c : 16;
> }
>
> struct SPacked {
> uint64 x : 32;
> uint64 a : 24;
> uint64 b : 24;
> uint64 c : 16;
> }
> ```
>
> Maybe the error only occurs if you specify a compiler switch?
It's clear how to get the desired portable layout.
Consider that nobody ever requested a warning on:
```
struct S {
uint x;
ulong y;
}
```
which is the equivalent. Not for D, C, or C++. At least none directed at my
compilers.
I would be good with a note about this technique in the specification.
P.S. We've already got soooo many compiler switches, adding another one needs a
strong case. Every such switch is a bug :-/
More information about the Digitalmars-d
mailing list