Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef function pointer recursive

Tags:

c++

c

I was trying to declare a function that takes a function of the same type as parameter.

void rec(void(*f)(void(*)(void(*)(...))))
{
    f(f);
}

I ended up making a recursive attempt.

You can always cast from a void*.

void rec(void* f)
{
    ((void(*)())f)(f);
}

But it's not type safe

I attempted to do this with a typedef:

typedef void(*RecFunc)(RecFunc);

But doesn't compile.

Is it possible to do it?

like image 801
tuket Avatar asked Dec 24 '22 06:12

tuket


2 Answers

You can't do what you are trying to do. As you noticed, you ended up trying to make a recursive typedef. That is not supported by the language.

like image 87
R Sahu Avatar answered Dec 28 '22 06:12

R Sahu


You can't do this directly in a conformant manner, but you can if you put the function pointer in a wrapper struct:

struct F;
typedef void(*RecFunc)(struct F *);

struct F {
    RecFunc f;
};

We first forward declare the struct so the typedef can use it. Then we define the struct to contain the function pointer. In this case the resursive function type is defined to take a pointer to struct F, but it will still work if it takes an instance of struct F.

Then you can use it like this:

void f(struct F *sf)
{
    static int x=5;

    if (x) {
        printf("x=%d\n",x);
        x--;
        sf->f(&(struct F){f});
    }
}

int main()
{
    f(&(struct F){f});
    return 0;
}

Output:

x=5
x=4
x=3
x=2
x=1
like image 39
dbush Avatar answered Dec 28 '22 06:12

dbush