Recursive function pointer type. How?

Doug Gwyn gwyn at smoke.brl.mil
Thu Mar 14 02:47:12 AEST 1991


In article <5144 at lure.latrobe.edu.au> ECSGRT at lure.latrobe.edu.au (GEOFFREY TOBIN, ELECTRONIC ENGINEERING) writes:
>One way *around* the problem is to use "typedef void (* state) ();",
>and cast the function return type, but I'd like to know whether
>anyone can construct a 'state' type as in the "machine" function.

A type along those general lines is the best that one can do, as C
does not fully support recursive types.  It does support some use
of incomplete types in recursive declarations where a structure (for
example) contains a pointer to its own type, but these escapes do
not help for declaring such recursive functions as in this example.
(The basic problem is that there is no way to declare an incomplete
type for use in the declaration that completes the type.)  What your
colleague is seeking is eminently reasonable, but in C a small
amount of kludgery is required in implementing the idea.

Here is an example of how one can obtain the desired behavior:

	typedef void (*state)(void);
	#define end_state ((state)0)	/* "end state" indicator */
	...
	extern state st_001(void);	/* typical state implementation */
	state start(void) {		/* "start state" implementation */
		...
		return (state)st_001;
	}
	...
	int main(void) {
		register state s;

		for (s = (state)start; s != end_state; )
			s = (*(state (*)())s)();  /* first "*" is optional */

		return 0;
	}



More information about the Comp.lang.c mailing list