5

How to define a pointer to function that returns a pointer to function?

typedef int(*a)(int,int);
a (*b)(int,int);

Why this can work,but the following can't work?

(int(*a)(int,int) ) (*b)(int,int);

or

int(*)(int,int) (*b)(int,int);

or

( int(*)(int,int) ) (*b)(int,int);
1
  • If you can, just stick with the typedef. Without it the syntax is wildly confusing - so much so that I don't want to attempt an answer from my phone at the risk of messing it up. Commented Feb 25, 2012 at 5:06

1 Answer 1

4

Here is the correct way to do it:

int (*(*b)(int,int))(int,int);

You can compile the following code that demonstrates using both of the methods. I would personally use the typedef method for clarity.

#include <stdio.h>

int addition(int x,int y)
{
    return x + y;
}

int (*test(int x, int y))(int,int)
{
    return &addition;
}

typedef int (*a)(int, int);

int main()
{
    a (*b)(int,int);
    int (*(*c)(int,int))(int,int);
    b = &test;
    c = &test;
    printf(b == c ? "They are equal!\n" : "They are not equal :(\n");
}
Sign up to request clarification or add additional context in comments.

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.