Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a pointer to function that returns a pointer to function

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);
like image 401
bitstore Avatar asked Oct 09 '22 13:10

bitstore


1 Answers

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");
}
like image 188
Justin Peel Avatar answered Oct 11 '22 04:10

Justin Peel