Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site sdcsvax.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!decvax!ittvax!dcdwest!sdcsvax!davidson From: davidson@sdcsvax.UUCP (Greg Davidson) Newsgroups: net.lang.c Subject: Re: goto variables? (state machines) Message-ID: <704@sdcsvax.UUCP> Date: Thu, 28-Feb-85 03:47:08 EST Article-I.D.: sdcsvax.704 Posted: Thu Feb 28 03:47:08 1985 Date-Received: Sat, 2-Mar-85 03:12:00 EST References: <8349@brl-tgr.ARPA> <986@reed.UUCP> Reply-To: davidson@sdcsvax.UUCP (Greg davidson) Distribution: net Organization: EECS Dept. U.C. San Diego Lines: 41 Keywords: tail recursion interpreter state machine Summary: Tail recursion optimization allows for clean state machines 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