Function pointers can be tricky to read. I start by reading the inner-most parenthesis, and work my way to the outer-most parenthesis.
Here's a breakdown of that declaration:
int (*h(int (*pf1)(), int (*pf2)()))()
(*pf1)()
and (*pf2)()
are pointers to functions that accept no parameters (i.e. ()), and both of them return an int
.
*h(int (*pf1)() , int (*pf2)())
is a function that accepts two function pointers that returnint
s. So, h returns a pointer to a function that accepts nothing and returns an int
Here is a link to some examples of the syntax, and a more elaborate breakdown:
https://www.cprogramming.com/tutorial/function-pointers.html
Added:
Since the original code that was provided segfaults, I wrote two different implementations that compare two integers and return the bigger one.
First, look at j
. It's just a regular function that accepts two parameters that happen to be function pointers. Those function pointers are then used within the function. And because we said j
returns an int
, we return the actual integer by calling pf1()
or pf2()
with ()
.
Now look at h
. In this scenario, h
is going to return a pointer *
. So we still call the function pointers pf1()
and pf2()
in h
, but when we return, we DO NOT use ()
because we want to return the whole function pointer (either pf1
or pf2
).
Lastly, look at main and see the difference between how j
and h
are used. Again, j
is just a regular function. However, h
uses the this syntax: h(f,g)() because h
returns a pointer to a function which we then want to call using ()
to get the actual integer result for printing.
Hope this helps provide a little more clarity with a working example! Good luck!
#include <stdio.h>
int f(){return 1;}
int g(){return 2;}
int j(int (*pf1)(), int (*pf2)())
{
return ((pf1() > pf2() ? pf1() : pf2()));
}
int (* h( int(*pf1)() , int(*pf2)() ) ) ()
{
return (pf1() > pf2() ? pf1 : pf2);
}
int main()
{
int res1 = j(f,g);
int res2 = h(f,g)();
//print values returned by calling f and g.
printf("f: %d \ng: %d\n", f(),g());
//print result of calling j(f,g)
printf("res1: %d\n", res1);
//print result of calling h(f,g)()
printf("res2: %d\n", res2);
return 0;
}