How do I cast to "pointer to function returning int" ?
Tim McDaniel
mcdaniel at amara.uucp
Fri Apr 13 10:16:48 AEST 1990
CMH117 at psuvm.psu.edu (Charles Hannum) writes:
Casting a void function to an int function is extremely non-portable.
Not quite. ANSI C, and many existing compilers, requires that
function pointers all be the same size. Any pointer to a function can
be cast into any other pointer-to-function type and back again,
producing the same pointer value. However, the value can't be called
while it is cast to a different type. For example:
typedef anytype (*PF_ANY )();
typedef othertype (*PF_OTHER)();
/*
* PF_ANY is the type "pointer to function () returning anytype".
* PF_OTHER is the type "pointer to function () returning othertype".
* Assume that anytype and othertype are different types.
*/
PF_ANY f1, f2;
PF_OTHER g;
...
g = (PF_OTHER) f1; /* legal under ANSI C */
f2 = (PF_ANY) g; /* legal under ANSI C */
if (f1 != f2) {
/* then this compiler is not ANSI C compliant. */
}
(*f2)(); /* exact same result as "(*f1)();" */
(*g)(); /* illegal under ANSI C */
And, by the way,
f2 = (PF_ANY) (void *) f1;
is illegal in ANSI C. "void *" is the universal pointer only for DATA
objects, not functions. You can convert any FUNCTION pointer to any
other FUNCTION pointer type.
To rephrase, then:
Casting a pointer to void function to a pointer to int function
type, and calling that result, is extremely non-portable.
--
Tim McDaniel
Applied Dynamics International, Ann Arbor, MI
Internet: mcdaniel%amara.uucp at mailgw.cc.umich.edu
UUCP: {uunet,sharkey}!amara!mcdaniel
More information about the Comp.lang.c
mailing list