
Pointer to function returning pointer to function returning...
Quote:
>[How do I declare a function such that this is legal?]
> P = P();
Ah, the recursive-function-type question. (Not quite frequent enough for the
FAQ.) I can think of two "clean" solutions, both of which require you to
modify your statement a bit.%
[0] Use the "wrong" type, and cast it. Here "funcp" can be any function
pointer type (it's going to be used as a generic, and never called); I prefer
to use "void (*)(void)", which in a sense is the simplest. Adding a second
typedef for the step-type, func_T (*)(void), may make this look nicer.
typedef void (*func_T)(void);
func_T (*P)(void);
func_T f(void) { ... return (func_T)f; }
for (P=f; P != (func_T (*)(void))0; P = (func_T (*)(void))(*P)());
[1] Create a recursive type using a one-element struct. This works because
you *can* define a structure type recursively. You may want to check whether
your compiler produces efficient code for this.
typedef struct step_T step_T;
struct step_T { step_T (*fn)(void); };
step_T (*P)(void);
step_T f(void) { step_T st; ... st.fn = f; return st; }
for (P=f; P != (step_T (*)(void))0; P = (*P)().fn);
Take your pick.
________
% Also, even though "P()" is a legal way to call through a function pointer in
ANSI C, I'm rewriting it as "(*P)()", partly to make it easier to port to
pre-ANSI compilers (you'll also have to remove the prototypes, of course),
and partly because many of us think that maintaining a syntactic distinction
between functions and function pointers is worth more than the three source
symbols per call that you save by doing it the other way.