C bitfields guarantees

Walter Bright newshound2 at digitalmars.com
Sat Jul 6 23:26:43 UTC 2024


On 7/5/2024 8:23 PM, Steven Schveighoffer wrote:
> On Saturday, 6 July 2024 at 00:16:23 UTC, Walter Bright wrote:
>> The following will also show discrepancies:
>>
>> ```
>> struct T {
>>     unsigned short x;
>>     unsigned int y;
>> }
>> ```
>>
>> for the same reason.
> 
> I tested this struct, and there were no discrepancies between compilers. All 
> compilers put 2 bytes of padding between the `ushort` and the `uint`.

Try it with a 16 bit compiler, which aligns on 16 bits rather than 32 bits.

No, I'm not cheating with this - I wanted to point out the consistency between 
32 bit compilers, despite the Standard saying nothing about it. But I can still 
break the example, with a 32/64 bit compiler:

```
struct U {
     unsigned int x;
     unsigned long y;
}
```

You'll get different sizes for 32 vs 64 bit compilations, including with D.



More information about the Digitalmars-d mailing list