Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!apple!bionet!ames!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: union or type casting, which to use? Message-ID: <28080@mimsy.umd.edu> Date: 29 Nov 90 08:32:38 GMT References: <9011271554.AA23331@bisco.kodak.COM> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 40 In article pds@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@cs.umd.edu Path: uunet!mimsy!chris