Path: utzoo!attcan!uunet!ns-mx!umaxc.weeg.uiowa.edu!williams From: williams@umaxc.weeg.uiowa.edu (Kent Williams) Newsgroups: comp.lang.c Subject: Re: Type of function returning function. Message-ID: <1852@ns-mx.uiowa.edu> Date: 13 Jul 90 13:48:20 GMT References: <1990Jul10.024205.17382@media.uucp> <20299@grebyn.com> Sender: news@ns-mx.uiowa.edu Reply-To: williams@umaxc.weeg.uiowa.edu.UUCP (Kent Williams) Organization: U of Iowa, Iowa City, IA Lines: 53 In article <20299@grebyn.com> ckp@grebyn.UUCP (Checkpoint Technologies) writes: >In article <1990Jul10.024205.17382@media.uucp> rmf@media.uucp (Roger Fujii) writes: >>So, just how does one type a function returning a pointer to a function? > ^^^^^^^^ This brings up an interesting conundrum: Suppose, for example, you want to implement a state machine as a set of functions. The strategy is for each function to return a pointer to the next function to be called, and let NULL indicate final state. So you have typedef SOMETYPE fp; fp state2(), state3(); fp state1() { return state2; } fp state2() { return state3; } fp state3() { return (fp)NULL; } void statemachine() { fp current; current = state1; while((current = (current)()) != NULL) ; } Simple enough, C-like enough, but you cannot specify SOMETYPE -- you get involved in an infinite regress! The problem is that you want to define SOMETYPE as typedef FUNCTION_RETURNING_POINTER_TO_SOMETYPE SOMETYPE; which is recursive -- so you have to do something like typedef void (*fp)(); and then use casts everywhere to make things come out right. The problem is that you can't do to function pointers what you can with structs -- make them self-referential. This is done in C by fiat -- you can refer to a pointer to a structure before the structure is fully specified, and refer to unspecified structure types generally -- e.g. You can do something like struct never_defined_anywhere; struct never_defined_anywhere *function_returning_pointer_to(); So long as you don't try to get any fields of never_defined_anywhere; -- Kent Williams 'Look, I can understand "teenage mutant ninja williams@umaxc.weeg.uiowa.edu turtles", but I can't understand "mutually williams@herky.cs.uiowa.edu recursive inline functions".' - Paul Chisholm