简体   繁体   中英

typedef function pointer recursive

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM