Alignment of unions

Stewart Gordon smjg_1998 at yahoo.com
Wed Apr 15 09:41:58 PDT 2009


Don wrote:
> Stewart Gordon wrote:
>> Don wrote:
<snip>
>>> 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.
>>
>> I still don't know what you mean.
> 
> You're acting as if there's a big difference between unions and structs, 
> and there isn't. Read the spec, the only differences are at 
> construction, and struct literals.

No, you have to add to that the differences inherited from C.  Moreover, 
what difference could possibly be bigger than that between the basic 
essence of structs and the basic essence of unions?

http://www.digitalmars.com/d/1.0/struct.html
"They work like they do in C, with the following exceptions:"

It's true that "alignment can be explicitly specified" is in there.  But 
I'm not sure that Walter really meant it to apply to unions as well as 
structs.  Especially given that it makes no comment (that I've found) on 
what align is meant to do in a union.  Moreover,

http://www.digitalmars.com/d/1.0/attribute.html#align
"Specifies the alignment of struct 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.
>>
>> If you don't know what the containing struct is, you probably also 
>> don't know what member alignment that struct requires. 
> 
> Yes you do. The union doesn't control the alignment of the surrounding 
> struct. It only controls the alignment of itself inside that struct.

I thought that was meant to be controlled by an align applied to the 
union instance as a member of the struct, rather than by an align 
applied to the union itself.  Only in the case of anonymous unions are 
they one and the same.

>> The person who creates the struct, OTOH, does know.
> 
> They do NOT know. Not without probing every member in the union.

?? ISTM all they really need to know is the overall size of the union, 
which is equal to the size of the union's largest member (which is easy 
to find out).

> So why are you trying to do that person's
>> job?
> 
> No, you know what alignment the member requires.
<snip>

What are the cases in which a member _requires_ a certain alignment?

OK, so there's one case: pointers in order to make sure the GC works 
properly.  But this is absolute alignment.  Maybe it's just me, but 
given that talk of alignment is nearly always in relation to structs, 
I'd made it out to be talking about relative alignment.  Maybe the spec 
just needs to be clearer....

Stewart.



More information about the Digitalmars-d mailing list