EDIT: It's been pointed out that this question is sort of confusing. The short version is: "why have a separate pointer variable (eg, fnPtr
) which points to a function (eg, fn
) when the function name fn
itself, without arguments, is already a pointer? /EDIT
I'm trying to understand something and could use feedback from the community regarding function pointers. (And while this might look like a duplicate of other questions on the topic, it really isn't, as least not that I could find.)
I understand the concept of a pointer to a function being used as an argument to another function as a callback...ie telling fn1
to use fn2
in some way during the execution of fn1
. What I don't understand is the complex syntax being used in all of it. If fn
is a defined function, then calling fn(...)
will execute the function with the supplied arguments. However, fn
used on its own is the address of the function, that is, a pointer to the function. Furthermore, fn
, &fn
, and *fn
are all the same thing. Why have dedicated function pointers, and why create new variable (ie, fnPtr
) which point to a function...the function name is already its own pointer!
This code compiles and works the same every time.
#include <stdlib.h>
#include <stdio.h>
int fn(int var) { //fn is a function which takes an int and returns an int
return var;
}
int (*fnPtrAmp)(int) = &fn;
int (*fnPtr)(int) = fn;
int needsCallback(int variable, int callback(int)) {
return callback(variable);
}
int needsCallbackPointer(int variable, int (*callbackPtr)(int)) {
return callbackPtr(variable);
}
int needsCallbackPointerWithDereference(int variable, int (*callbackPtr)(int)) {
return (*callbackPtr)(variable);
}
int main() {
printf("%d\n", fn(4));
printf("%d\n", fnPtr(4));
printf("%d\n", (*fnPtr)(4));
printf("%d\n", needsCallback(4,fn));
printf("%d\n", needsCallbackPointer(4,fnPtr));
printf("%d\n", needsCallbackPointer(4,fn));
printf("%d\n", needsCallbackPointer(4,&fn));
printf("%d\n", needsCallbackPointerWithDereference(4,fnPtr));
printf("%d\n", needsCallbackPointerWithDereference(4,fn));
printf("%d\n", needsCallbackPointerWithDereference(4,&fn));
return 0;
}
The simplest syntax is that of needsCallback
but that isn't done anywhere, it's always needsCallbackPointer
and fnPtrAmp
. Why? With needsCallback
you don't even have to define an extra variable to be the function pointer. As I said before, the function name is its own pointer!
Could use some feedback...thanks.