Union type conversions

Joseph Nathan Hall jnh at ece-csc.UUCP
Sat Jul 16 00:56:05 AEST 1988


In article <12490 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
 >In article <19845 at watmath.waterloo.edu> atbowler at watmath.waterloo.edu
 >>(Alan T. Bowler [SDG]) writes:
 >>... 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) writes:
 >Sorry, you're just plain wrong here.  From page 140 of K&R, I quote:
 
 ... from the *de*scriptive part of the text, which says only that
 
 >	"In effect, a union is a structure in which all members have
 >	 OFFSET ZERO [emphasis added] ..."
 
 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.  Alan Bowler is right; unions make few
 guarantees.  On the other hand, a compiler that does not conserve
 storage with union definitions is probably not worth using.

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.)

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."

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."  Maybe there
is a badly-behaved compiler out there that does, but in that case it's not
a "real" C compiler.

'Nuff said on my account.  I'd like to see comments from others ...

-- 
v   v sssss|| joseph hall                      || 201-1D Hampton Lee Court
 v v s   s || jnh at ece-csc.ncsu.edu (Internet)  || Cary, NC  27511
  v   sss  || the opinions expressed herein are not necessarily those of my
-----------|| employer, north carolina state university . . . . . . . . . . . 



More information about the Comp.lang.c mailing list