Recursive function pointer type. How?

Christopher R Volpe volpe at camelback.crd.ge.com
Wed Mar 13 08:35:31 AEST 1991


In article <5144 at lure.latrobe.edu.au>, ECSGRT at lure.latrobe.edu.au
(GEOFFREY TOBIN, ELECTRONIC ENGINEERING) writes:
|>Conceptually, and in skeleton form:
|>
|>	#include <stdio.h>
|>	typedef state (*state)();  /* Wrong, but conveys the intent */
|>
|>	void
|>	machine (state s)
|>	{
|>		while (s != NULL)
|>			s = (*s)();  /* This is what we want */
|>	}
|>
|>So each state in the machine is a function pointer.  The pointed-to
|>function performs some action, then returns the next state.
|>
|>One way *around* the problem is to use "typedef void (* state) ();",
                                                  ^^^^
If the return value is void, there's nothing there to cast. I think
you meant: "typedef void *(*state)()".

|>and cast the function return type, but I'd like to know whether
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      this wouldn't be strictly conforming.

|>anyone can construct a 'state' type as in the "machine" function.
|>----------------------------------------------------------------------

This came up a while ago and I posted a solution. I don't know
if this is exactly what you want, but it's as close as I could
come up with. 

You can take advantage of the self referential abilities of
structs to do what you want with functions without any typecasts,
although it is debatable whether or not the following is any
less kludgy (it does compile under gcc, though):

typedef struct somestruct {
    struct somestruct (*field)();
    } fp;

fp f1(),f2();

fp f1()
{
  fp dummy;
  dummy.field=f2;
  return dummy;
}

fp f2()
{
  fp dummy;
  dummy.field=f1;
  return dummy;
}

void statemachine() {
                fp (*current)();
                current = f1;
                while((current = (current)().field) != NULL)
                                ;
}

===================
Chris Volpe
G.E. Corporate R&D
volpecr at crd.ge.com



More information about the Comp.lang.c mailing list