Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 772
iammilind Avatar asked Jan 17 '26 18:01

iammilind


1 Answers

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(); }
like image 92
Joseph Mansfield Avatar answered Jan 20 '26 09:01

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!