But I'm wondering can you have an array that holds function-pointers of different types?
As noted in Anatoly's answer, your code doesn't work because your array intends to declare contain pointers-to-functions that return void
, but then you try invoking it as a pointer-to-function that returns int
. These are incompatible types, so an explicit cast is required. And, as noted in section 6.3.2.3/8 of the ISO C99 standard, casting a function pointer to a different function pointer type and back again is permitted:
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.
That said, I don't see any point to doing this. The function pointer cast is a static cast (a cast known to the compiler) and not a dynamic cast, so you must manually keep track of which elements in your array are of type void (*)()
and which are of type int (*)(int, int)
. It'd instead be simpler to have a separate array for each function pointer type and avoid casting altogether. Doing so would be less error-prone since you would not risk invoking a function pointer as the wrong type (which would be undefined behavior).
Update:
You've changed your question so that array
is now an array of void*
pointers. Note that although normal pointers may be freely cast to and from void*
, this is not true for function pointers (although it is considered to be a common extension in many implementations).