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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With