%p and different pointer representations

Doug Gwyn gwyn at smoke.BRL.MIL
Fri Mar 3 00:44:24 AEST 1989


In article <928 at jhunix.HCF.JHU.EDU> ins_balb at jhunix.UUCP (Andy Matter) writes:
>I need a few things clarified; I don't have a copy of the standard,
>and a few people have said mutually contradictory things.  So tell me
>if the following is right:
>Any object or incomplete pointer fits in (void *).

Yes, any POINTER to an object or to an incomplete type after conversion
to void* and back and will still compare equal to the original.

>Any object or inconplete pointer fits in (char *).

Yes, but you have to exert some care to get it into or out of one.
In particular, you have to use casts.

>Any function pointer fits in any other function pointer.

Yes, but you have to exert some care.
In particular, you have to use casts.

By the way, to USE a pointer, it has to be of the right type at the
place it is used.  It is best and simplest to maintain pointers as
their correct types all along, rather than unnecessarily mapping
them back and forth into other types.  For one thing, if you use
proper types everywhere, the compiler can help detect usage errors.

>Function pointers do not have to fit into (void *) (or vice-versa).

Yes.

>Also, how's this for a solution:
>#if sizeof (void *) > sizeof (void (*)())
>#define generic_ptr (void *)
>#else
>#define generic_ptr (void (*)())
>#endif
>Then use generic_ptr instead of void *, and any pointer type
>(including pointers to functions) will fit (as long as you remember to
>cast everything you assign).

Won't work.  There is no guarantee that an object pointer can be
converted to a function pointer or vice-versa.

>I guess the best solution would have been to continue using char * as
>a generic object pointer, to make all function pointer the same size,
>and to make void * big enough to hold either.  Someone should have
>thought of that earlier, I guess....

"Someone" did think of it, and realized that it wasn't acceptable.

I don't understand why so many people seem to be concerned about
packing both object AND function pointers into the same type of
variable.  (By the way, it CAN be done; use a union.)  What sort
of program calls for such weirdness, anyway?  The only genuine
"problem" I've seen mentioned is the inability to portably print
out a function pointer, something I don't think is all that useful.



More information about the Comp.lang.c mailing list