5

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.

Community
  • 1
  • 1
CuriousSid
  • 534
  • 3
  • 11
  • 25

2 Answers2

6

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

LihO
  • 41,190
  • 11
  • 99
  • 167
2

To declare a function returning a pointer to a function, first write the declaration of the function type to be returned. For example, the type of a function accepting two int and returning an int is:

int function(int, int)

Now, make it a pointer to a function by inserting *. Since the precedence gets in the way (the parenthesized function parameters will bind more tightly to the identifier than the * does), we have to insert parentheses too:

int (*function)(int, int)

Finally, replace the identifier with the declarator of the factory function. (For this purpose, the declarator is the function identifier and the parameter list.) In this case, we replace function with factory(int). This gives:

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

This declares a function, factory(int), that returns something that fits the spot where xxx is in int (*xxx)(int, int). What fits in that spot is a pointer to a function taking two int and returning an int.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312