[net.lang.c] goto variables?

alexis@reed.UUCP (Alexis Dimitriadis) (02/25/85)

> > 	main()
> > 	{
> > 		int *a;
> > 
> > 	b:
> > 		a = b;
> > 		printf("a = 0x%x\n", a);
> > 	}
> > 
> > (NOTE: This was compiled under 4.2BSD on a -750)
> > 
> > This compiles and runs perfectly.  However, when adding an obvious statement
> > (namely, "goto *a") it won't let us compile it.  It seems like the compiler
> > will *almost* let us do this.
> > 
> > What I want to know is, "can this be easily added to the language?",
> > "Is it a reasonable thing to add?".  Comments anyone?
> 
> Technically it is illegal to assign `a=b', [...]
> Try using setjmp/longjmp to do this.
> 

  Is it a reasonable thing to add?  A goto that uses a variable like
would be the equivalent of a calculated goto (or something like that) in
Fortran.  I doubt the C language needs a lot of gotos.

alx
PS Sorry for the long context quote.

davidson@sdcsvax.UUCP (Greg Davidson) (02/28/85)

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