goto variables? (state machines)

Greg Davidson davidson at sdcsvax.UUCP
Thu Feb 28 18:47:08 AEST 1985


One of the biggest sources of goto's and monolithic code is in the
implementation of state machines, e.g., for interpreters.  It is the
only fast way of implementing them in C.  But label variables are not
the best solution.

If the language standard required C compilers to optimize tail recursion
into jumps, then it would be possible to cleanly implement state machines
with one function for each state.  For example:

state1()
{
   ... do stuff ...
   state2();	/* state1's stack frame will be reused here because */
   return;	/* the compiler sees state1 has nothing more to do */
}

This is an example where an optimization issue severely impacts the
usage of the language.  Without a guarantee of tail recursion optimization,
you have to optimize the one function per state code into:

	* * *
	state1: ... do stuff ...
		goto state2;
	* * *
	state2: ....
	* * *

Note that if time is not of the essence, for example in scanners,
you can do state machines like this:

void (*state)();	/* state points at the state transition fn */

state = start;
while (state)
    state = (*state)();	/* each state fn returns a ptr to the next one */

Unfortunately, this is much slower.  So the only question is:  How do we
convince the people writing the language spec to require efficient handling
of tail calls?

_Greg



More information about the Comp.lang.c mailing list