A
ais523
I've been doing this sort of thing, and I want to know if it's a
sensible way to act (I think this is correct and portable, but want to
make sure):
int f(int a, void(*b)())
{
static int x=0;
if(x) return a;
x=1;
/* do something with a */
((void(*)(int, void(*)()))b)(a,b);
x=0;
return a;
}
Is this one of the few cases where a cast is actually necessary? The
idea is that b should be of the same type as f, so it can be called
with itself as an argument, but there's no way to write that directly
with a finitely-long prototype. One solution might be to do without
prototypes (I'm not sure if that would work), but I don't really want
to do that. So the other solution's to use a pointer of the wrong
type; void* can't be used because it might not be able to represent a
function pointer, so I used void(*)() (should I have used void(*)
(void) instead?). Is this the right, portable way to go about this? (I
don't write code like (void(*)(int, void(*)())) very often.) Likewise,
is my static int the best way to go about preventing an infinite
regress? (The semantics of the situation are that I want the function
to just return a if it's called a second time from within itself.)
sensible way to act (I think this is correct and portable, but want to
make sure):
int f(int a, void(*b)())
{
static int x=0;
if(x) return a;
x=1;
/* do something with a */
((void(*)(int, void(*)()))b)(a,b);
x=0;
return a;
}
Is this one of the few cases where a cast is actually necessary? The
idea is that b should be of the same type as f, so it can be called
with itself as an argument, but there's no way to write that directly
with a finitely-long prototype. One solution might be to do without
prototypes (I'm not sure if that would work), but I don't really want
to do that. So the other solution's to use a pointer of the wrong
type; void* can't be used because it might not be able to represent a
function pointer, so I used void(*)() (should I have used void(*)
(void) instead?). Is this the right, portable way to go about this? (I
don't write code like (void(*)(int, void(*)())) very often.) Likewise,
is my static int the best way to go about preventing an infinite
regress? (The semantics of the situation are that I want the function
to just return a if it's called a second time from within itself.)