Type of function returning function.

Christopher R Volpe volpe at underdog.crd.ge.com
Tue Jul 17 03:13:16 AEST 1990


In article <1852 at ns-mx.uiowa.edu>, williams at umaxc.weeg.uiowa.edu (Kent
Williams) writes:
> 
> 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)
> 				;
> }
> 

Minor point, but "current" doesn't hold an fp, it holds the address
of a function returning an fp, right? 

                fp (*current)();


Also, 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