0
int g()
{
    return 0;
}

int f1(int(fn)())
{
    return fn();
}

int f2(int(*fn)())
{
    return fn();
}

int main()
{
    f1(g);
    f2(g);
}

The code above can be sucessfully compiled.

I just wonder:

What's the difference between int f(int(fn)()) and int f(int(*fn)())?

Why does both of them are legal in C++?

xmllmx
  • 37,882
  • 21
  • 139
  • 300

1 Answers1

4

int f(int(fn)()) and int f(int(*fn)()) are the same thing. A function takes a function pointer as parameter.

When we pass the name of a function as parameter, the function name is automatically converted to a pointer. So

int f(int(fn)()) {}
int f(int(*fn)()) {}  // redefinition error
for_stack
  • 17,274
  • 3
  • 30
  • 41