union or type casting, which to use?

Chris Torek chris at mimsy.umd.edu
Wed Dec 5 00:03:04 AEST 1990


In article <28080 at mimsy.umd.edu> I wrote:
>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). ...
>
>	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? */
>	);

Tony Hansen sent me an interesting argument based on the idea of
`incomplete structure pointers'.  Given a module.h that declares:

	struct xyz;
	typedef struct xyz *hidden_t;
	hidden_t newxyz(void);
	void xyz(hidden_t), endxyz(hidden_t);
	#define NOXYZ ((hidden_t)0)

and a separate module that uses it, it becomes clear that at least
nil pointers to `xyz' structures must be known/knowable `outside'
the module that actually defines them.  With some stretching (and
the use of `void *' intermediaries), the argument can be extended
to non-nil pointers as well.

There is, however, a counterargument that applies to both of these.
There is no rule that says that the compiler must generate real code
until it `has all the pieces'.  `cc -c foo.c' might write a foo.o
that contains an intermediate form, and only when foo.o is `linked'
with module.o (which actually defines `struct xyz') are the pointers
given final types, and only then would the compiler generate the
machine instructions needed to use those pointers.

This argument might even obviate the need to make all struct pointers
the same `size'.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list