The C standard doesn't allow casting even void *
to a pointer to a function or back again - the wording for void *
is in 6.3.2.3p1:
A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
However, functions are not objects so you cannot even cast a function pointer to void *
portably.
Now, it is said that a pointer can be converted to an integer, and back again, though:
6 Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
If your (function) pointers are say 64 bits and int
32 bits, the behaviour is undefined. For pointers to objects you can use (u)intptr_t
- but this is not guaranteed to work with function pointers. Instead for function pointers it is guaranteed that you can cast any function pointer to another, so you can use a generic function pointer, for example
typedef void (*funcptr)(void);
and cast this to the proper function-pointer-type before calling.
If you need an integer too, then you must use an union
union int_or_funcptr {
int integer;
funcptr function;
}
and if the function is needed, assign or read the function
member of the union, casting it properly prior to calling it.