casting to/from union types

Stephen Clamage steve at taumet.COM
Sat Jun 2 01:21:53 AEST 1990


In article <523 at cpsolv.CPS.COM> rhg at cpsolv.uucp (Richard H. Gumpertz) writes:
[ to cast from a component type to the union type ... ]
>one has to allocate a temporary and then assign to the temporary.
>...
>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?

You can already do this in C++.  You define a conversion function as part
of the union.  You could get the same effect in C by writing a conversion
function:
	union U { int i; /* etc */ };
	union U convert_int_to_U(int i)
	{
		union U u;
		u.i = i;
		return u;
	}

It seems unnecessary to invent an extension to C to accomodate what must
be a very unusual operation.  If you don't explicitly declare a temp
and assign to it, the compiler has to do it for you, and the generated
code comes out the same.  (If you pass an int, but the largest member of
the union is bigger than that, not enough will have been passed as the
parameter.)  So the most you save is a line of source code.

But maybe what you really want to do could be accomplished by writing a
variadic function instead of one taking a union:

	enum WhatKind { intkind, doublekind, longkind, /* etc */ };
	SomeType funny_func(WhatKind, ...);
	void foo()
	{
		SomeType s = funny_func(doublekind, 2.0);
	}
-- 

Steve Clamage, TauMetric Corp, steve at taumet.com



More information about the Comp.lang.c mailing list