Goto considered helpful

James D. Allen jamesa%betelgeuse at Sun.COM
Tue May 24 12:22:04 AEST 1988


	The `goto' flames seem to be dying out; I'd like to add some
gasoline.  While others have been defending relatively `structured' goto's
(eg, "break 2", common code coalescing) my favorite goto is really horrendous:
a jump from one inner loop to a different inner loop.  I am sincerely curious
if there is a "better way."
	Following is edited but fairly faithful pseudocode for a contract
bridge endgame analysis program.  Since performance is an issue I mention that
the pseudostatements each compile to very terse machine code.

	initialize;
	for (tricknum = 0; outcome still undecided; tricknum++) {
		for (player = winner of prev trick; other players; player++) {
			determine legal plays;
			remove redundancies;	/* A == K , etc. */
			select most likely play;
		    BACKTRACK:
			play the card;
			push set of legal plays;
			if (player == winner of previous trick)
				restrict others to suit_led;
		}
		determine winner of trick;
	}
	while (--tricknum >= 0) {
		for (player = last_to_play; other players; player--) {
			pop set of legal plays;
			undo played_card and delete from legal plays;
			if (player is on losing side && other play available)
				goto BACKTRACK;
		}
	}
	print solution;


	Here are some alternate coding methods with my objections.

1) Do a recursive function call for each played card.  Clumsy (you either
	have to pass a lot of arguments or maintain the data as globals).
	Execution time increases significantly.
2) Do a recursive function call for each trick.  Reasonable, but doesn't
	completely sidestep the problem since backtracking occurs *within*
	a trick.
3) Rewrite in Prolog.  Plausible but pedantic.
4) Stuff the forward loop into the middle of the backtrack loop, or
	vice versa (left as an exercise).  Requires clumsy boolean flags
	(my code uses none).  Less readable because intuitively the forward
	and backtrack loops are separate.

	I don't claim that this is a general solution for backtracking.
Simpler problems can be handled nicely with nested `while's; harder problems
will require a more general method.  But for this program, depicting the
backtracking with a single powerful "goto" expresses the paradigm more
clearly (and certainly more efficiently) than the alternatives.



More information about the Comp.lang.c mailing list