Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!wuarchive!texbell!sugar!ficc!peter
From: peter@ficc.uu.net (Peter da Silva)
Newsgroups: comp.os.minix
Subject: Re: gotos
Message-ID: <6377@ficc.uu.net>
Date: 2 Oct 89 11:16:21 GMT
References: <24962@louie.udel.EDU> <1989Sep29.183703.1275@utzoo.uucp> <1764@psueea.UUCP>
Organization: Xenix Support, FICC
Lines: 65

In article <1764@psueea.UUCP>, kirkenda@psueea.uucp (Steve Kirkendall) writes:
> I can't remember the last time I used a goto as anything except a multi-level
> "break" or "continue" instruction.

There is one other condition where a goto is justified: in implementing a
state machine.

C is not the best language for implementing state machines, but still there
are three main approaches for doing the job. Each has its place:

(1) The big switch.

	This is what YACC and LEX use, and is appropriate for computer-
	generated state machines. There is no need for gotos here (yes,
	I know the standard yacc engine has gotos... it needn't).

(2) The subroutine approach.

	This is a good one for large human-generated state machines, where
	the majority of the code is in the states... not in the state
	machine. You basically do this:

		while( (*state)(...) != FINISHED )
			continue;

(3) The fast approach.

	If you need a really fast state machine, take a look at the typical
	big switch. The code looks like:

		while(state != FINISHED) {
			switch(state) {
				case STATE0: ...
					if(this) state = STATETHIS;
					else if(that) state = STATETHAT;
					else state = STATEELSE;
					break;
				...
			}
		}

	This is isomorphic with:

		STATE0:
			...
			if(this) goto STATETHIS;
			else if(that) goto STATETHAT;
			else goto STATEELSE;
		...

		FINISHED:

	A very good compiler could turn the one into the other, and a
	pretty good compiler would probably blow off optimising the
	latter. But for the sort of program that uses this (device driver,
	embedded processor) you tend not to trust optimisers anyway.

Now, I'm sure I'll be flamed to death for this. C'est la vie. It's an awfully
obscure situation, and in fact I've never written code like this myself. I have
seen it, though, and there really wasn't any alternative.
-- 
Peter da Silva, *NIX support guy @ Ferranti International Controls Corporation.
Biz: peter@ficc.uu.net, +1 713 274 5180. Fun: peter@sugar.hackercorp.com. `-_-'
"That is not the Usenet tradition, but it's a solidly-entrenched            U
 delusion now." -- brian@ucsd.Edu (Brian Kantor)