Ptr to func doesn't like casting??

Kevin Martin kpmartin at watmath.UUCP
Mon Dec 3 00:51:27 AEST 1984


>I am morally bound to tell you that you are sinning :-), and in
>a somewhat unportable way.  Pointers to functions and pointers to data
>are very different animals, and on some machines they are of different
>sizes.  Using one to hold the other is hazardous.  I believe the ANSI C
>draft outlaws such conversions altogether, although I haven't got my
>copy handy to check.  Use a union; it's much more portable, and should
>shut the compilers up as a useful bonus.
>				Henry Spencer @ U of Toronto Zoology

I always had the impression K&R didn't make an exception for function
pointers when it stated that different pointer types can be cast into
each other. Oh well.

I am certainly aware of machines where using a function pointer cast to
call a function as if it returned a different type would lead to disaster.
But on these machines, you could cast the pointer all you wanted to,
as long as it came back to the original type before being used for a
function call.

What does the ANSI committee suggest for a generic function pointer? Or
does (void *) still work?

Using a union is not always a practical solution. For instance, in
a library routine which takes as an argument a function pointer, for
later use by the caller (not the callee). You would have to have a union
of all possible types of functions. Even if the library routine restricts
the types that the function can return, you still need to be able to
"cast" the supplied function pointer into the union.
e.g. I can't say
	libfunc( (void *)myfunc );
instead, I must say
	union functypes junk_variable;
	junk_variable.ret_type_1 = myfunc;
	libfunc( junk_variable );

(Another example might be some sort of dynamic-linking function or
overlay loader which returns a pointer to the loaded function. Surely
such a beast cannot return a union of *all* types of functions!)

Are there machines which cannot cast a function pointer into another
pointer (e.g. (void *)) and back? After all, you can cast any pointer
into an implementation-dependant integral type and back without loss
of information...
                      Kevin Martin, UofW Software Development Group.



More information about the Comp.lang.c mailing list