iammilind
iammilind

Reputation: 69988

Different function pointer syntax(s) as an argument to another function

int func ()
{
  printf("foo()\n"); 
  return 0;
}

void foo1 (int (*pf)()) { pf(); }
void foo2 (int (pf)()) { pf(); }
void foo3 (int pf()) { pf(); }

int main ()
{
  foo1(func);
  foo2(func);
  foo3(func);
}

What is the difference between the argument passed to foo1(), foo2() and foo3().
All 3 syntax compiles fine in g++ and behaves in a same way. Are all 3 called function pointer technically?
Tagged with C as it applicable to that as well.

Upvotes: 3

Views: 116

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

There is no difference between them. The first argument is a pointer to function type, while the other two are just two ways of writing the same function type. However, in the same way that array type arguments are adjusted to be pointers, function type arguments are adjusted to be pointers to functions. From C++11 §8.3.5/5:

After determining the type of each parameter, any parameter of type [...] “function returning T” is adjusted to be [...] “pointer to function returning T,”

Or from C99 §6.7.5.3/8:

A declaration of a parameter as “function returning type” shall be adjusted to “pointer to function returning type

So the second and third function declarations have their argument type adjusted to be identical to the first.

Note that you can put as many parentheses as you like around the identifier and it will still be the same function type:

void foo2 (int (((((pf)))))()) { pf(); }

Upvotes: 7

Related Questions