Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration of function returning a function pointer

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.

like image 629
CuriousSid Avatar asked Feb 17 '23 00:02

CuriousSid


1 Answers

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 :)

like image 182
LihO Avatar answered Mar 04 '23 11:03

LihO