Type of function in relation to type of function pointer

I am 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 the same with 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 compilation error for goo = blah . But in the first example, I could call the function g (blah) , which seems to be very similar to goo = blah . Why does one work and not the other?

+6
source share
2 answers

Somewhat confusing, you can declare a function to accept a function as a parameter (although this does not make sense), and the effect should make the parameter a function pointer. This is similar to how you can declare a function parameter that looks like an array, but is actually a pointer.

A function argument can be a function name, with or without & , to explicitly accept its address. If you omit & , that is, an implicit conversion between lines. Again, this is similar to passing (a pointer to) an array, where an implicit conversion between strings and pointers means that you only need to write the name of the array, not &array[0] .

This rule does not apply when declaring variables; int goo(int); (with or without extra parentheses around goo ) declares a function, not a pointer, and you cannot assign functions.

+7
source

This is similar to the difference between an array and a pointer, for example. if you have:

 char *foo; char bar[N]; 

You can do:

 foo = bar; 

but you cannot do:

 bar = foo; 

When a function type is used in the declaration of an argument, it is translated into an equivalent function pointer, just like a declaration:

 void fun(int arr[]); 

translates to:

 void fun(int *arr); 
+1
source

All Articles