Put your code... (was Re: gotos

kenny at uiucdcsb.cs.uiuc.edu kenny at uiucdcsb.cs.uiuc.edu
Tue Apr 26 11:03:00 AEST 1988


[Part 6. Panic exits]

The notion of using a _goto_ for a panic exit condition is touched on
by Knuth only in passing.

There are many cases, generally ignored in the academic training that
computer scientists receive, where a complicated operation can be
interrupted by the occurrence of an unexpected condition.  Generally,
the result of such an interruption, in classroom exercises, is to
terminate the program.  Simply aborting is, however, unacceptable in
the real world; for instance, a text editor that aborts (and quite
possibly destroys the user's file) when the user makes an error (or
the system detects one) is nearly unusable.

Unquestionably, a program that can encounter an unexpected condition
in an inner structure can recover by testing for that condition in all
the containing structures.  Such tests, usually written as statements
like

	if (error_detected) break;

	while (... && !(error_detected)) ....
	
	error_detected != do_function (....)

both clutter the code and are a decided performance expense at run
time, as they repeat the tests for errors in all the loops of the
program.

In many of these cases, it is advisable to, instead of repeating
tests, simply insert code of the form

	if (failure) goto error_handler;

at the point where the failure can occur.

The `C' idiom does not use the evil word _goto_ for this construct,
since the transfer is normally out of the lexical scope, and quite
possibly out of the source file.  Rather, the usual way to do it in
`C' is to use the constructs _setjmp_ and _longjmp._

Moral: Using _goto_ may be acceptable to break a deep nest of control
structures in the event of an unusual occurrence.  This usage is quite
possibly the only acceptable context for _goto_.

[End of part 6.]



More information about the Comp.lang.c mailing list