I'm trying to understand the difference between the following two blocks of code:
void f(int (*func)(int))
{
func(5);
}
and
void g(int (func)(int))
{
func(5);
}
Both functions work in the same way given the following code:
int blah(int a)
{
cout << "hello" << endl;
return 0;
}
int main()
{
f(blah);
g(blah);
return 0;
}
However, if I write the following code:
int (*foo)(int);
int (goo)(int);
foo = blah;
goo = blah;
I get a compile error for goo = blah. But in the first example, I could call make the function call g(blah) which appears to be quite similar to goo = blah. Why does one work and not the other?
Originally Answered: What is the difference between pointer to function and function pointer? A function pointer points to the memory address, where the function's code is stored. So unlike other functions function pointer points to code rather than data. e.g.
A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.
CServer Side ProgrammingProgramming. Function Pointers point to code like normal pointers. In Functions Pointers, function's name can be used to get function's address. A function can also be passed as an arguments and can be returned from a function.
A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.
Somewhat confusingly, you can declare a function to take a function as a parameter (even though that makes no sense), and the effect is to make the parameter a function pointer. This is similar to the way you can declare a function parameter that looks like an array, but is actually a pointer.
The function argument can be the name of the function, with or without a &
to explicitly take its address. If you omit the &
, then there's an implicit function-to-pointer conversion. Again, this is similar to passing a (pointer to) an array, where the implicit array-to-pointer conversion means you only need to write the array's name, rather than &array[0]
.
That rule doesn't apply when declaring variables; int goo(int);
(with or without unnecessary parentheses around goo
) declares a function, not a pointer, and you can't assign to functions.
It's analogous to the difference between an array and a pointer, e.g. if you have:
char *foo;
char bar[N];
you can do:
foo = bar;
but you can't do:
bar = foo;
When the function type is used in an argument declaration, it's translated to the equivalent function pointer, just as declaring:
void fun(int arr[]);
is translated to:
void fun(int *arr);
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