Why is there an error while declaring a generic pointer to a function?
Because there exist no such thing as a generic pointer to a function in the C language. void*
is a generic pointer to an object (a variable). void*
can only be used generically with object pointers, never with function pointers.
It is possible however to cast between one function pointer to another, but when you call the actual function, you must do so through the correct function pointer type.
You have various other mistakes regarding not allocating memory etc that are addressed by other answers. But lets ignore all of that, as well as the use of function pointers which doesn't really fill a purpose in this case. What you actually want to do can be achieved with modern standard C in the following manner:
#include <stdio.h>
int sum_int(int a, int b) {
return a + b;
}
int sum_intp(const int *a, const int *b) {
return *a + *b;
}
#define sum(a,b) ( (void)_Generic((b), int:0, int*:0),/*NOTE: comma operator*/ \
_Generic((a), \
int: sum_int, \
int*: sum_intp)(a,b) )
int main(void)
{
int a=10;
int b=20;
printf("%d\n", sum(a, b));
printf("%d\n", sum(&a, &b));
//printf("%d\n", sum(a, &b)); //compiler error
//printf("%d\n", sum((float)a, b)); //compiler error
return 0;
}
The C11 _Generic
macro determines types at compile-time. The pseudo code for the macro is:
- Check if argument b is a valid type.
- Discard the value from this argument b check - it's just there to generate a compiler error in case of wrong types.
- Comma operator.
- "Check if argument a is valid too, then call the correct function based on the type of a.
This is type safe and removes the need for void*
or function pointers.