Using gcc test.cpp , I get:
test.cpp: In function 'void execute(void* (*)())': test.cpp:12:22: error: invalid conversion from 'void*' to 'void (*)()' [-fpermissive] test.cpp: In function 'int main()': test.cpp:18:19: error: invalid conversion from 'void (*)()' to 'void* (*)()' [-fpermissive] test.cpp:9:6: error: initializing argument 1 of 'void execute(void* (*)())' [-fpermissive]
The signature for argument f is invalid. You have to use
void execute(void (* f)())
instead of this. Therefore, when assigning john you do not need a cast:
john = f
Alternatively, you can simplify this by calling f directly:
f(); // execute function pointer
EDIT: Since you want to use void pointers, you need to pass f as the void pointer:
void execute(void *f)
Here you will need the john assignment, but since f already void * , you do not need to do the translation.
NOTE: Given that you are passing a pointer to void, the execute function will accept something and you will have runtime errors if you pass the wrong thing. For instance:
void print_name(const char *name) { printf("%s", name); } void execute1(void *f); void execute2(void (*f)()); int main() { int value = 2; execute1(&value);
Using a specially defined function pointer allows the compiler to generate an error at the point where you passed the wrong type of argument. This is recommended for run-time crashes, because a run-time crashes can be used as a security vulnerability and requires extensive testing so that this error does not occur.
reece source share