Path: utzoo!news-server.csri.toronto.edu!rutgers!att!linac!pacific.mps.ohio-state.edu!zaphod.mps.ohio-state.edu!rpi!crdgw1!camelback!volpe From: volpe@camelback.crd.ge.com (Christopher R Volpe) Newsgroups: comp.lang.c Subject: Re: Recursive function pointer type. How? Message-ID: <17534@crdgw1.crd.ge.com> Date: 12 Mar 91 22:35:31 GMT References: <5144@lure.latrobe.edu.au> Sender: news@crdgw1.crd.ge.com Reply-To: volpe@camelback.crd.ge.com (Christopher R Volpe) Lines: 69 In article <5144@lure.latrobe.edu.au>, ECSGRT@lure.latrobe.edu.au (GEOFFREY TOBIN, ELECTRONIC ENGINEERING) writes: |>Conceptually, and in skeleton form: |> |> #include |> 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@crd.ge.com