C bitfields guarantees
Timon Gehr
timon.gehr at gmx.ch
Sun Jul 7 10:42:22 UTC 2024
On 7/7/24 06:47, Walter Bright wrote:
> On 7/6/2024 8:50 PM, Steven Schveighoffer wrote:
>> Let's take another example:
>>
>> ```c
>> struct U {
>> unsigned int x;
>> unsigned long long y: 30;
>> unsigned long long z: 34;
>> }
>>
>> struct U2 {
>> unsigned int x;
>> unsigned long long y: 34;
>> unsigned long long z: 30;
>> }
>> ```
>
> Simple solution:
> ...
You said: Same type, same alignment. It's clearly not true in Steven's
example. It seems alignment depends on bit width.
Also consider this:
```d
struct S{
uint x;
ulong y:30;
ulong z:34;
}
pragma(msg, S.y.offsetof, " ", S.y.alignof); // 4LU 8LU
The offset of `y` does not even respect its alignment! This is insanity.
It also happens with `uint`:
```d
struct S{
ushort x;
uint y:16;
}
pragma(msg, S.y.offsetof, " ", S.y.alignof); // 2LU 4LU
```
I.e., "stick to `int`/`uint` bitfields, things will be predictable" is
not even true. They may be laid out differently based on what's before them.
> ```
> struct U {
> unsigned int x;
> unsigned int y:30;
> unsigned long long z:34;
> }
> ```
>
> or:
>
> ```
> struct U2 {
> unsigned int x;
> unsigned int pad;
> unsigned long long y:30;
> unsigned long long z:34;
> }
> ```
>
> depending on which layout is desired. This is simple,
If it is simple, you should have no trouble stating how it works
completely in a couple sentences.
> predictable, and
> portable. It's not going to be a mystery to anyone reading the code -
> it's eminently readable.
> ...
Walter, this is frustrating. It is only obvious to you because having
reverse-engineered and implemented it, you already know how it works.
Note that the things you were saying earlier suggested it would actually
work differently in Steven's example. I hope you understand that this is
confusing. I am as a result now not sure whether what you stated is the
full truth, or it is still some inadmissible simplification that glosses
over some further dragons.
Also, I hope `.offsetof % .alignof != 0` is just a bug in your bitfield
implementation.
More information about the Digitalmars-d
mailing list