[comp.lang.c] unions or void * to transmit "generic" pointers

evil@arcturus.UUCP (Wade Guthrie) (09/13/89)

I'm curious about whether it is okay to use a void * to transmit pointers
between functions (when the func's agree on the type, but the at least one
of the functions needs to be able to handle all sorts of DATA pointers) or
whether it is more correct/portable to use unions of pointers.  

Specifically, I want to do something like:

Routine()
{
	sometype *stuff; /* a pointer to where to put the data */

	. . .

	/* this routine needs to ask the user for some data, so it
	 * will call a menu routine
	 */

	Menu( (void *) stuff, type);
}

Menu(point, type)
void * point;
int type;
{
	. . .
	switch(type)
	{
	case SOMETYPE:
		*((sometype *) point) = /* something appropriate */

	. . .
}

So, do I pass a union of pointers (seems pretty cumbersome) instead, or can 
I do the above?


Wade Guthrie
evil@arcturus.UUCP
Rockwell International
Anaheim, CA

(Rockwell doesn't necessarily believe / stand by what I'm saying; how could
they when *I* don't even know what I'm talking about???)

gwyn@smoke.BRL.MIL (Doug Gwyn) (09/14/89)

In article <6003@arcturus> evil@arcturus.UUCP (Wade Guthrie) writes:
>I'm curious about whether it is okay to use a void * to transmit pointers
>between functions (when the func's agree on the type, but the at least one
>of the functions needs to be able to handle all sorts of DATA pointers) or
>whether it is more correct/portable to use unions of pointers.  

Any object pointer is guaranteed to be coercable into a generic pointer
(void* for Standard C, char* for older C) or a pointer to a smaller-or-
same-size type with the same or less stringent alignment restrictions,
then converted back again, without loss of significant information.
Thus your example is proper.

However, conversion from one pointer type to another need not be a "free"
operation; the representation may have to be reformatted.  Thus, using a
union can provide a performance advantage, since it bypasses any change
of representation.

evil@arcturus.UUCP (Wade Guthrie) (09/16/89)

Thanks to all for answers.  There were so many, I thought I'd post it.
Wade Guthrie evil@arcturus.UUCP