Alignment of unions

Don nospam at nospam.com
Tue Apr 14 08:37:58 PDT 2009


Stewart Gordon wrote:
> Frits van Bommel wrote:
>> Stewart Gordon wrote:
> <snip>
>>> But the offset of a union member is always zero.  So what would this do?
>>
>> It should make sure the union is aligned appropriately in a containing 
>> struct, meaning U.alignof >= M.alignof for all members M. Specifying 
>> per-member alignment allows you to change that member's effect on the 
>> union's alignment.
> 
> But alignment of a member within a structure and alignment of the whole 
> structure relative to an outer one are two distinct concepts.  What 
> sense is there in being able to use one to control the other?
> 
>>>> Most obviously, a union U consisting of a single member x should have
>>>> U.alignof == x.alignof.
>>> <snip>
>>>
>>> Yes, by propagating the union's alignment (relative to the containing 
>>> struct) to the member.
>>
>> But the union's alignment needs to be sufficient for all members, so 
>> it depends on the maximum alignment of all members.
> 
> That's only because you want to be able to attach alignments to 
> individual members of a union.  And I still don't know why.

I'm not sure why you think unions are so different to structs. They are 
identical in most respects -- including requirements for alignment of 
members.

> 
> If you want a union to have a certain alignment relative to a struct in 
> which it's contained, in what cases is it not sufficient to put the 
> align attribute on the union's instance in the struct?

In cases where you don't know what the containing struct is. The union 
may just be a type returned from a template, for example.



More information about the Digitalmars-d mailing list