union or type casting, which to use?

Chris Torek chris at mimsy.umd.edu
Thu Nov 29 19:32:38 AEST 1990


In article <PDS.90Nov27180241 at lemming.webo.dg.com>
pds at lemming.webo.dg.com (Paul D. Smith) writes:
>In your case, you have no problem: the union elements are both the
>same size and are guaranteed by ANSI to be compatible with a cast:
>both are pointers. [details deleted, see original article]

Are you certain?

I think that it is possible to conclude, given nothing more than
X3.159-1989 and `ANSI standard nomenclature', that all struct pointers
*are* the same size, but that it is *not* possible to conclude that
they have the same format (e.g., different types might use different
bits, where struct pointers to A use the low bits and struct pointers
to B use the high bits).  I think you also cannot conclude that

	struct i { int x; };
	struct c { char x; };
	union u { struct i *i; struct c *c; } u;
	struct c foo;

	foo.x = 'a';
	u.i = (struct i *)&foo;
	printf("u.c->x = %c\n",
	    u.c->x				/* ERROR? */
	);

will work.  In particular, the line marked `ERROR?' *might* be guaranteed
to work if you change it to

	    ((struct c *)u.i)->x

since the `struct c *' cast `undoes' any effect that the `struct i *'
cast might have had (e.g., shifting the bits around to use low or high).

It *is* true that there are very few, if not none at all, implementations
in which the line marked `ERROR?' will in fact fail.  But I think it is
not guaranteed.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list