Union type conversions

Chris Torek chris at mimsy.UUCP
Fri Jul 22 08:19:32 AEST 1988


>>>In article <19845 at watmath.waterloo.edu> atbowler at watmath.waterloo.edu
>>>>(Alan T. Bowler [SDG]) wrote:
>>>>... there is no guarantee that the compiler does not simply do the
>>>>equivalent of `#define union struct' ...

>>In article <3714 at ece-csc.UUCP> jnh at ece-csc.UUCP (Joseph Nathan Hall)
>>answered with a quote from K&R 1st ed., p. 140:
>>>	"In effect, a union is a structure in which all members have
>>>	 OFFSET ZERO [emphasis added] ..."

>In article <12490 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) I said:
>>The point of this quote is to warn users that writing on any one
>>element of a union *may* stomp any other element, not that it *must*
>>stomp other elements. ...

In article <3717 at ece-csc.UUCP> jnh at ece-csc.UUCP (Joseph Nathan Hall)
continues:
>The description of unions in K&R (1st ed.; I don't have the 2nd close by
>to look at) is, I agree, somewhat vague.  But it specifically states, in
>the passage I quoted above, that all of the members start at offset
>zero ... don't you think this implies, without ambiguity, that the members
>of a union will a) be allocated space starting at the same address, and b)
>that they will have in common the first n bytes of storage, where n is the
>size of the smallest item?  (Notwithstanding cases where you have unions
>of structs where storage isn't contiguously allocated, of course.)

I am not sure.  In particular, if there is no testable assertion that
makes a union different from a structure, then a compiler that implements
a union as a structure will not break any (testable) rules and will
thus be correct.

>Also, on p. 197 of the 1st ed., "A union may be thought of as a structure
>all of whose members begin at offset 0 and whose size is sufficient to
>contain any of its members.  At most one of the members can be stored in
>a union at any time."

This is a bit stronger (being in the prescriptive text), but `may be
thought of' is not the same as `is'.

>I don't see how you can come up with the liberal interpretation that a
>compiler following the K&R standard could "#define union struct."

Write some correct code that produces a wrong answer if a union of a
set of elements were implemented as a structure containing all the
elements, and you will have a proof.  As it is, the only thing I can
come up with is this:

	union {
		int a;
		int b;
	} x;
	...
	x.b = 0;
	x.a = 123;
	assert(x.b == 123);

which I am not certain is guaranteed (by K&R 1st ed., at least) to work.
If it did not, it would violate the Rule of Least Astonishment, but that
rule does not appear in the text. . . .
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list