Union element alignment query

Mark Brader msb at sq.sq.com
Thu Nov 22 14:14:40 AEST 1990


> > union {
> > FOOTYPE	a[4];
> > BARTYPE        b;
> > } combo;
> > Does the standard guarantee 
> > (void *)(&combo.a[0]) == (void *)(&combo.b) ?
> 
> Not exactly.  The standard (section 3.5.2.1) requires that
> 	(FOOTYPE*)&combo == &combo.a[0]

No, combo.a is the union member, not combo.a[0].  So this should be:

	(FOOTYPE(*)[4])&combo == &combo.a

The actual wording in 3.5.2.1 is:

#  A pointer to a union object, suitably converted, points to each
#  of its members (or if the member is a bit-field, then to the unit
#  in which it resides), and vice versa.

One sticking point is the meaning of "suitably converted".  When I
casually read this before, I assumed that converting either pointer
to void * would be "suitable".  (The other pointer in the comparison
would then be implicitly converted to void * also.)  In that case,
 
	&combo == (void *)&combo.a
and	&combo == (void *)&combo.b

and therefore

	(void *)&combo.a == (void *)&combo.b

But the stricter interpretation, guaranteeing only

	(FOOTYPE(*)[4])&combo == &combo.a
and	(BARTYPE *)&combo == &combo.b
and	&combo = (union ... *)&combo.a
and	&combo = (union ... *)&combo.b

also seems to be legitimate.  We'd have to have an interpretation ruling
to settle this, I think.  Anyway, note the last two equalities.  They
imply that

	(void *)(union ... *)&combo.a == (void *)(union ... *)&combo.b

but, as there isn't any direct guarantee that

	(void *)(TYPE *)foop == (void *)foop

, this probably doesn't help.

Likewise, there is no guarantee that a pointer to an array, suitably
converted, points to its first element, or vice versa.  That is, even if

	(void *)&combo.a == (void *)&combo.b

is true, the equality originally asked about does not seem to follow.

It is, of course, possible that some of these things are indirectly
guaranteed, and I haven't noticed.

-- 
Mark Brader		"'Settlor', (i) in relation to a testamentary trust,
Toronto			 means the individual referred to in paragraph (i)."
utzoo!sq!msb, msb at sq.com		-- Income Tax Act of Canada, 108(1)(h)

This article is in the public domain.



More information about the Comp.lang.c mailing list