union.sizeof

kinke via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Mar 25 16:36:07 PDT 2017


On Saturday, 25 March 2017 at 22:45:22 UTC, ketmar wrote:
> zabruk70 wrote:
>
>> //DMD 2.073.1 and latest 2.075.0-master-972eaed
>> //Windows 7 32-bit
>>
>> union Union1
>> {
>>    align(1):
>>    byte[5] bytes5;
>>    struct
>>    {
>>      align(1):
>>      char char1;
>>      uint int1;
>>    }
>> }
>>
>> void main ()
>> {
>>    import std.stdio: writefln;
>>    writefln("Union1.sizeof=%d", Union1.sizeof);  //prints 8, 
>> not 5
>> }
>>
>> I expect size of Union1 is 5 (5 bytes == char + uint == 5).
>> Is this my bug or DMD?
>
> `align(1) union Union1` will do the trick.
>
> what you did is members packing. but the union itself is padded 
> to integer size too. i.e. internal `align` will set aligning 
> for *members*, and external `align` will change padding of the 
> whole thing.

The union should have an implicit alignment of 1 already though, 
right? It's defined as the maximum of all member alignments, and 
both the bytes5 array and the anonymous struct members have an 
explicit alignment of 1. The alignment of the anonymous struct's 
int1 member (explicitly 1 too) shouldn't even matter.


More information about the Digitalmars-d-learn mailing list