Function declaration returning a function pointer

While reading this article, I came across the following declaration of function pointers. I have not worked with such declarations, but I interpret it this way: the return value of functionFactory when dereferencing is a function that takes 2 ints and returns int.

int (*functionFactory(int n))(int, int) { printf("Got parameter %d", n); int (*functionPtr)(int,int) = &addInt; return functionPtr; } 

I was curious to know if such an expression is specific to this case or if there is a general methodology that I skipped.

I mean, we usually see declarations like

 <returnType> funcName(listOfArgs){} 

This one is getting out of the league. Can someone comment.

+4
source share
2 answers

usually we see declarations like <returnType> funcName(listOfArgs){}

Yes, but in this case, the return type is a pointer to a function, and this is really one of the possible ways to define such a function:

 int (*functionFactory(int n))(int, int) { ... } 

Fortunately, you can create an alias for any type using typedef , which makes it a lot easier:

 typedef int (*FncPtr)(int,int); FncPtr functionFactory(int n) { printf("Got parameter %d", n); FncPtr functionPtr = &addInt; return functionPtr; } 

which is much easier to read, and also easier to understand. And the prototype form of the function is similar to how you expected it to look like this: it is a function called functionFactory , which takes 1 argument of type int and returns FncPtr :)

+5
source

To declare a function that returns a pointer to a function, first write the declaration of the return type of the function. For example, the type of a function that takes two int and returns int :

 int function(int, int) 

Now make it a function pointer by inserting * . Since priority interferes (function parameters in brackets will be more closely tied to the identifier than * ), we must also insert parentheses:

 int (*function)(int, int) 

Finally, replace the identifier with the declarator of the factory function. (To this end, the declarator is a function identifier and a list of parameters.) In this case, we replace function with factory(int) . This gives:

 int (*factory(int))(int, int) 

Declares a factory(int) function that returns what matches the place where xxx is in int (*xxx)(int, int) . What fits in this place is a function pointer with two int and returns an int .

+2
source

All Articles