Function pointers as parameters in C ++?

I am confused by the form of parameters for function pointers. The following two:

int fun(int (*g)()) { cout << g() << endl; } int fun(int g()) { cout << g() << endl; } 

Both of these definitions work well. But, as you noticed, there are some differences in the prototypes of these two functions:

  • the first takes an int (*g)() parameter,
  • and the second takes an int g() parameter.

My question is, is there any difference between the two?

+4
source share
3 answers

In the second case, the type of function is configured to become a pointer to a function, which makes both functions identical.

 int fun(int (*g)()); int fun(int g()); //same as above, after type adjustment 

The C ++ 03 standard states in ยง13.1 / 3,

Declarations of parameters that differ only in this are a type of function, and the other is a pointer to the same type of function equivalent . That is, the type of function is configured to become a pointer to the type of function (8.3.5) .

 [Example: void h(int()); void h(int (*)()); // redeclaration of h(int()) void h(int x()) { } // definition of h(int()) void h(int (*x)()) { } // ill-formed: redefinition of h(int()) ] 

The same as setting the array to a pointer, with which we are more familiar:

 int fun(int *a); int fun(int a[]); //same as above, after type adjustment int fun(int a[10]); //same as above, after type adjustment 

All are the same!

Here you can answer a few questions:

+4
source

In fact, you cannot have a function type parameter. The function parameter, declared as if it is of the type "returning the function T", is set to the type "pointer to the return function T". So your two definitions are virtually identical. (C has the same rule.)

A similar rule applies to array parameter declarations. For instance:

 int main(int argc, char *argv[]); 

really means the following:

 int main(int argc, char **argv); 
+2
source

Most compilers (e.g. MSVC, g ++) accept the second form as abbreviated for the first. From a technical point of view, you should always use the first form.

+1
source

All Articles