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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

What is addInt?
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.