While reading this article, I came across the following declaration of function pointers. I haven't worked with such declarations, but the way I interpret it is that: the returned value of functionFactory when dereferenced is a function accepting 2 ints and returns an int.
int (*functionFactory(int n))(int, int) {
printf("Got parameter %d", n);
int (*functionPtr)(int,int) = &addInt;
return functionPtr;
}
I was curious to know whether such a declaration is specific to this case or is there a generic methodology that I have missed.
I mean we normally see declarations like
<returnType> funcName(listOfArgs){}
This one appears out of league. Could someone please elaborate.
we normally see declarations like
<returnType> funcName(listOfArgs){}
Yes, but in this case the return type is a pointer to function and this is really one of the possible ways how to define that kind of function:
int (*functionFactory(int n))(int, int) {
...
}
Luckily you are able to create an alias for any type using typedef
that makes it much simpler:
typedef int (*FncPtr)(int,int);
FncPtr functionFactory(int n) {
printf("Got parameter %d", n);
FncPtr functionPtr = &addInt;
return functionPtr;
}
which is far easier to read and also easier to understand. And the form of the function prototype is just like you expected it to look like: It is the function called functionFactory
that takes 1 argument of type int
and returns FncPtr
:)
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