gotos

Daniel R. Levy levy at ttrdc.UUCP
Sun Apr 10 13:50:48 AEST 1988


In article <5170 at ihlpg.ATT.COM>, tainter at ihlpg.ATT.COM (Tainter) writes:
# In article <4347 at ihlpf.ATT.COM>, nevin1 at ihlpf.ATT.COM (00704a-Liber) writes:
# > In article <2556 at ttrdc.UUCP> levy at ttrdc.UUCP (Daniel R. Levy) writes:
# > |I know this battle is an old chestnut, but for the record do you guys believe
# > |that superfluous flags and great big if-then statements are truly superior
# > |to the goto?  (And the break, which is a goto by another name.)  E.g.:
# > |	while (loopcond) {
# > |		for (i=0; i<limit; i++)
# > |			if (frob(i) == TRUE)
# > |				goto loopagain;	/* nice and CLEAN!!! */
# > |		.../* lots and lots of code over many pages */...
# > |loopagain:	;
# > |	}
# > Opinion:  this is an example of FORTRAN disguised as C.
# >  In this particular case, using a continue statement
# > inside in your Fortran-type example instead of a goto is much more preferable.
# 
# Except of course that that wouldn't work since it is nested under a second loop.
# This is the only alternative to using a flag on the lines of the alternative
# code.
# [ Flag riddled code at indentation >> removed ]
# > Opinion:  this is an example of Pascal disguised as C.
# >  _ __			NEVIN J. LIBER	..!ihnp4!ihlpf!nevin1	(312) 510-6194
# People, listen closely, GOTOs are not inherently bad.  If used carefully
# as in this example they are quite reasonable and really not hard to follow.
# Of course, they would be much harder to understand if they didn't use
# mnemonics and instead used numbers ala Pascal or ForTran.
# --j.a.tainter

Somebody mailed me a much better form of what I was trying to do:

	while (loopcond) {
		for (i=0; i<limit && frob(i)!=TRUE; i++)
			;
		if (i<limit)
			continue;
		...
	}

This IS just as clean, just as fast, and doesn't involve any gotos.  The
picture gets muddier when you have multiple nested loops however:

	while (loopcond) {
		for (i=0; i<ilimit; i++)
			for (j=0; j<jlimit; j++)
				for (k=0; k<klimit; k++)
					if (frob(i,j,k)==TRUE)
						goto loopagain;
		/* lotsa code */
loopagain:	;
	}

Getting out of this one without gotos requires continual testing of a flag
in the for loops:

	/* look ma, no gotos! */
	while (loopcond) {
		bustout=FALSE;
		for (i=0; i<ilimit && bustout==FALSE; i++)
			for (j=0; j<jlimit && bustout==FALSE; j++)
				for (k=0; k<klimit; k++)
					if (frob(i,j,k)==TRUE) {
						bustout=TRUE;
						break;
					}
		if (bustout==TRUE)
			continue;
		/* lotsa code */
	}

Trouble with this method is that you lose some performance.  What's a hacker
to do?  :-) :-) :-)
-- 
|------------Dan Levy------------|  Path: ..!{akgua,homxb,ihnp4,ltuxa,mvuxa,
|         an Engihacker @        |  	<most AT&T machines>}!ttrdc!ttrda!levy
|     AT&T Data Systems Group    |  Disclaimer?  Huh?  What disclaimer???
|--------Skokie, Illinois--------|



More information about the Comp.lang.c mailing list