goto in C (was fallthrough)

Richard A. O'Keefe ok at quintus.UUCP
Tue Mar 8 10:47:05 AEST 1988


In article <25348 at cca.CCA.COM>, g-rh at cca.CCA.COM (Richard Harter) writes:
> Currently I average about one goto per 10,000 lines of code, all of them
> being transfers to a procedure epilog, e.g
> 
> foobaz() {
>   ....
>   allocate space and other setup
>   ....
>   if (some_special_condition) goto wrapup;
>   ....
> wrapup:
>   deallocate space and other cleanup
>   }
> 
> But do people actually use it to any signifigant extent?  Why not just
> drop it?
> -- 

I very often write code of the form

sometype foo()
    {
	int state = 0;

	<side effect 1>	/* open file, or allocate memory */
	state = 1;
	<side effect 2>	/* same sort of thing */
	...
	state = N;
	<return new object>
    ERROR:	
	switch (state) {
	    case N:	/* undo side effect N */
			/* falls through to */
	    case N-1:   ...


	    case 1:	/* undo side effect 1 */
	    case 0:	/* return error code */
	}
    }

If you are trying to write code that other people can use,
it really isn't good manners to lose chunks of memory just
because you couldn't open a file.  One of these per library
package, and one per program, doesn't seem excessive.

This is a sufficiently stylised approach that it could be replaced by
some other mechanism.  (Nested exception handlers?  C++ destructors?
unwind-protect?)  But in a language like C, why not just keep the goto?
{Actually, a break-from-labelled-statement would work too, but that's
just another goto.}

There's another reason for retaining the goto.  Look at the output of
YACC some time.  I counted five labels in yyparse(), but may have
missed some.  It isn't just people who write C, you know!  Why shouldn't
people be allowed to write compilers which generate C?



More information about the Comp.lang.c mailing list