So I've got the following expression:
int (*f1(int(*a)(int, int))) (int, int);
and I'm trying to make sense out of it, but it's confusing. I figured out that "a" is a pointer to a function which takes 2 arguments(int, int). Then f1 seems to be a pointer to another function that takes 2 int arguments. But what's confusing me is how f1 relates to a.
Can someone give me some hints or properly explain what the above expression is doing?
In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type.
It is basically used to store the address of a function. We can call the function by using the function pointer, or we can also pass the pointer to another function as a parameter. They are mainly useful for event-driven applications, callbacks, and even for storing the functions in arrays.
Function Pointers in C and C++ A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.
The tip in C is to read a declaration as it were an expression. This is this famous symmetrie that make C elegant.
How to read it? following the operators precedence rules:
*a
: if I dereference variable a
;(*a)(int,int)
: and then call it with two integers;int (*a)(int,int)
: then I get an integer;So a
is a pointer to a function taking two int
s as parameter and returning an int.
Then:
f( int(*a)(int,int) )
if I call f with the argument a
;*f( int(*a)(int,int) )
and then I dereference the result;(*f( int(*a)(int,int) )(int,int)
and then call this result with 2 int
as argumentint (*f( int(*a)(int,int) )(int,int)
I get an int
So f
is a function taking an a
as argument and returning a pointer to a function that take two int
s as argument and returning an int
. So f
return type is the same as its argument return type. It could have been simpler:
using ftype = int(*)(int,int);
ftype f( ftype a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With