Assuming that all functions share the same return type, is it valid to call each one by a "generic" function pointer, that is declared with empty parentheses (so it does not specify its arguments)?
Here is an example code, that illustrates it:
#include <stdio.h>
void fun1(void)
{
printf("fun1\n");
}
void fun2(int a)
{
printf("fun2: %d\n", a);
}
void fun3(int a, int b)
{
printf("fun3: %d %d\n", a, b);
}
int main(void)
{
void (*pf)(); // pseudo-generic function pointer
pf = fun1;
pf();
pf = fun2;
pf(0);
pf = fun3;
pf(1, 2);
return 0;
}
You may do similar stuff, but not exactly that way. When you call a function through a function pointer you have to be sure that the prototype on the calling side is exactly as the function was defined.
Now a function declarations with empty parenthesis isn't even a prototype, so this is not the right way to call it. The main reason is that the calling convention might be slightly different than you'd expect. For ()
functions special rules apply, namely narrow types are converted to int
, unsigned
or double
.
Now what you may do is store a function pointer in pf
as you do, but then you'd always have to convert it back to the correct function pointer before the call, such as
((void (*)(int, int))pf)(a, b);
This is barely readable and much errorprone. You should avoid such gymnastics as much as you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With