Type of function returning function.

Kent Williams williams at umaxc.weeg.uiowa.edu
Fri Jul 13 23:48:20 AEST 1990


In article <20299 at grebyn.com> ckp at grebyn.UUCP (Checkpoint Technologies) writes:
>In article <1990Jul10.024205.17382 at media.uucp> rmf at 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 at umaxc.weeg.uiowa.edu    turtles", but I can't understand "mutually 
williams at herky.cs.uiowa.edu      recursive inline functions".' - Paul Chisholm



More information about the Comp.lang.c mailing list