function returning pointer to itself

William E. Davidsen Jr davidsen at steinmetz.ge.com
Thu Jul 14 00:21:43 AEST 1988


In article <5485 at batcomputer.tn.cornell.edu> olson at tcgould.tn.cornell.edu (olson) writes:
| Does the new C standard have a natural way to declare a
| function that returns a pointer to itself
| ????

  Three solutions come to mind. The first may only be used if all
procedures are global. This may not always be the case, as you may want
to return pointers to static functions.

int do_state_1(), do_state_2();
int (*foo[])() = {
	do_init(),
	do_state_1,
	do_state_2
};
int next_state = 0;
.
.
	next_state = (*foo[next_state])();

  This can either set the next_state as a global from the procedure, or
an int state may be returned.

method two:

void do_init();
void (*foo)() = do_init;
.
.
	(*foo)();

  And each procedure sets foo to the next state.

method three:

  This is close to what you want, but gives warnings on some compilers.
I would not use it personally for portability reasons.

int (*do_init)();
int (*next_state())();
.
	next_state = (int (*)()) (*next_state)();

  The assumption is that a pointer to a function returning any one thing
looks like a pointer to a function returning some other thing. I can't
think of any reason this wouldn't be true, but I don't trust it.

  I personally like method two best, then one. If you have some old
archives (ie. net.something) I posted my Turing machine in C using a
modified method one and two, where the pointer was pointing a a STATE
struct, gotten by an index.
-- 
	bill davidsen		(wedu at ge-crd.arpa)
  {uunet | philabs | seismo}!steinmetz!crdos1!davidsen
"Stupidity, like virtue, is its own reward" -me



More information about the Comp.std.c mailing list