简体   繁体   中英

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 these two definitions work well. But as you have noticed, there are some differences in the prototypes of these two functions:

  • the first one takes parameter int (*g)() ,
  • while the second takes parameter int g() .

My question is are there any difference between them?

In the second case, the function type adjusts to become pointer-to-function-type , which makes the both function identical.

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

The C++03 Standard says in §13.1/3,

Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent . That is, the function type is adjusted to become a pointer to function type (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())
]

It's same as with array to pointer adjustement, with which we're 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 same!

You can a detail answer by me here:

You can't actually have a parameter of function type. A function parameter declared as if it were of type "function returning T" is adjusted to be of type "pointer to function returning T. So your two definitions are effectively identical. (C has the same rule.)

A similar rule applies to array parameter declarations. For example this:

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

really means this:

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

Most compilers (eg MSVC, g++) accept the second form as a shorthand for the first. Technically speaking you should always use the first form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM