casting to/from union types

Richard H. Gumpertz rhg at cpsolv.CPS.COM
Thu May 31 13:31:30 AEST 1990


It is possible to effectively cast a union type to one of its component types
by appending ".X" where X is the name of the component.  Unfortunately, there
is no way to do the reverse cast; instead one has to allocate a temporary and
then assign to the temporary.  For example, to pass an int I to a function
that takes a union argument, one might use:
	extern int I;
	typedef union { int I; float F; } U;
	extern foo(int which, U x);
	U tempU;

	foo(1, (tempU.I = I, tempU));

A much cleaner syntax (to read) might be:
	foo(1, (U)I);

A problem arises is if one wants to pass a constant: the type of constants is
non-intuitive.  For example, if we change the above typdef to
	typedef union { int I; float F; char C; } U;
and then call
	foo(3, (U)'X');
then should the 'X' be effectively assigned to the I field or the C field?

I suppose we could disambiguate between th I and C fields using a whole new
kludge like
	foo(3, (U.C)'X');
but that seems ugly.

Does anybody have a better idea as to how one might allow casting arguments
to functions that accept union types without having to allocate a temporary?
The details are non-obvious.  Could the people on the net invent an extension
that would read cleanly, maybe get some trial use, and perhaps even be
proposed for inclusion for C-95 or whatever?

Please reply via e-mail and I will summarize.

-- 
  ==========================================================================
  | Richard H. Gumpertz    rhg at CPS.COM    (913) 642-1777 or (816) 891-3561 |
  | Computer Problem Solving, 8905 Mohawk Lane, Leawood, Kansas 66206-1749 |
  ==========================================================================



More information about the Comp.lang.c mailing list