# I used GOTO!

**URL:** <https://boards.straightdope.com/t/i-used-goto/312648>\
**Category:** Miscellaneous and Personal Stuff I Must Share\
**Created:** [July 15, 2005, 2:36pm UTC](https://boards.straightdope.com/t/i-used-goto/312648 "2005-07-15T14:36:00Z")\
**Posts on this page:** 15\
**Page:** 3

<div class="post-metadata">

**Author:** ![ioioio](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/ioioio/32/316_2.png) [@ioioio](https://boards.straightdope.com/u/ioioio)\
**Post date:** [July 17, 2005, 3:40pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/41 "2005-07-17T15:40:26Z")

</div>

Assume one common\_event and two possible rare\_events.  
If coded thusly . . .

```auto

 
IF common_event ORIF rare_event1 ORIF rare_event2         
      WRITE_AUDIT code                
ENDIF                             

```

. . . the compiler would generate the following eight machine language instructions:

Test for common\_event  
Branch to WRITE\_AUDIT if condition met  
Test for rare _event1  
Branch to WRITE\_AUDIT if condition met  
Test for rare_ event2  
Branch to EXIT if condition not met  
WRITE\_AUDIT: code  
EXIT: code

**RESULTS**  
If common\_event true: 4 instructions executed  
If only rare\_event2 true: 8 instructions executed  
If no cases true: 6 instructions executed

Coded your way, the following 14 machine language statements would be generated:

Set flag to false  
Test for common\_event  
Branch to TEST2 if condition not met  
Set flag to true  
Branch to WRITE\_AUDIT  
TEST2: Test for rare\_ event1  
Branch to SETFLAG if condition met  
TEST3: Test for rare\_ event2  
Branch to WRITE\_AUDIT if condition NOT met  
SET\_FLAG: Set flag to true  
WRITE\_AUDIT: Test flag  
Branch to EXIT if flag not on  
write\_audit code  
EXIT: code

**RESULTS**  
If common\_event true: 9 instructions executed  
If only rare\_event2 true: 12 instructions executed  
If no cases true: 10 instructions executed

Your _best_ case scenario executes more machine instructions than the worst case scenario using a compound IF statement. (I’m not saying that the single compound IF statement is the best way to code here – I’m using it to demonstrate efficiency.)

Your grade:  
Consistency of style: F  
Maintainability: D  
Efficiency: F  
Elegance: F  
Impressing anyone who’s been coding for more than a couple of weeks: F  
_I have, however, enjoyed the geek fest._

---

<div class="post-metadata">

**Author:** ![UncleRojelio](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/unclerojelio/32/3160_2.png) [@UncleRojelio](https://boards.straightdope.com/u/UncleRojelio)\
**Post date:** [July 17, 2005, 5:16pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/42 "2005-07-17T17:16:40Z")

</div>

If [Edsger W. Dijkstra](http://www.acm.org/classics/oct95/) says gotos are bad, that is good enough for me.

---

<div class="post-metadata">

**Author:** ![MaxTheVool](https://avatars.discourse-cdn.com/v4/letter/m/9fc29f/32.png) [@MaxTheVool](https://boards.straightdope.com/u/MaxTheVool)\
**Post date:** [July 17, 2005, 5:40pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/43 "2005-07-17T17:40:04Z")

</div>

> [@robardin](#):
>
> What’s wrong with that? Maybe I’m just used to it, but I find this as much or more readable/understandable than the GOTO version.

It has many extra comparisons, and will execute more slowly.

> [@](#):
>
> And really, the most readable approach would be one that put the whole bit of code that is doing the lookup in some sensibly subroutine like “findThing()” and just have code that goes:

True, although again that’s going to be marginally less efficient, execution-wise.

I think the game industry is one of few places where even rare GOTOs are OK (and remember, I’m not FOR them, as I’ve only used them once or twice in 10 years), in that (a) performance is always paramount, (b) code rarely has to hang around for 15 years, and (c) bugs are never life-threatening.

> [@](#):
>
> PS - A minor side pet peeve, but I _detest_ so-called “Hungarian notation” for variables like “bFound”. I find all the type-prefixing annotation just so much clutter. Isn’t a name like “found” already clear enough? And what happens if you change a variable’s type, like changing a customer\_id field from integer to string?

Eh. I’m used to that style now. And if you change customer\_id from an integer to a string, then it’s USEFUL to change it’s name so the compiler will automatically find all occurrences of it for you, so you can make sure you’re not now doing something that no longer works since its type has changed 🙂

---

<div class="post-metadata">

**Author:** ![ultrafilter](https://avatars.discourse-cdn.com/v4/letter/u/3d9bf3/32.png) [@ultrafilter](https://boards.straightdope.com/u/ultrafilter)\
**Post date:** [July 17, 2005, 5:45pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/44 "2005-07-17T17:45:13Z")

</div>

> [@MaxTheVool](#):
>
> Eh. I’m used to that style now. And if you change customer\_id from an integer to a string, then it’s USEFUL to change it’s name so the compiler will automatically find all occurrences of it for you, so you can make sure you’re not now doing something that no longer works since its type has changed 🙂

If you change something from an integer to a string, the compiler will probably point out all its uses even if the name doesn’t change. The only case where you’d have to worry about something like that is if you’re changing from one fundamental type to another.

IMO, the type of a variable should be obvious from its name (and perhaps a little bit of domain expertise). If not, it’s most likely poorly named.

---

<div class="post-metadata">

**Author:** ![Orbifold](https://avatars.discourse-cdn.com/v4/letter/o/779978/32.png) [@Orbifold](https://boards.straightdope.com/u/Orbifold)\
**Post date:** [July 17, 2005, 6:29pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/45 "2005-07-17T18:29:30Z")

</div>

I do use goto, but very rarely. My personal rules for goto (which aren’t original, but I can’t remember where I picked them up) are: (a) never use a goto to jump backwards, (b) never use a goto to jump into a scope, only out of one, and © never use a goto if there’s another control structure which does the same job. Which pretty much reduces it to a poor man’s exception handling, i.e. for processing string input:

```auto

for( this ){
  if( that ){
    while( the_other_thing ){
      // ...
      if( error ) goto LINE_ILL_FORMED;
      // ...
    }
    while( some_other_thing_besides ){
      // ...
      if( error ) goto LINE_ILL_FORMED;
      // ...
    }
  }
}
return success;

LINE_ILL_FORMED:
// Recover from error, free resources, blah blah blah
return failure;

```

I suppose I could use actual structured exception handling, but that would be overkill: no data needs to be transmitted with the exception and the error never, ever gets propagated out of the function scope, so why incur the overhead of the -fexception flag? Copying the error-handling code to every location where I might put a goto would be a maintenance nightmare, and wrapping it in a function would require pushing who knows how much data onto the stack. If the language I’m using has labelled blocks and labelled break statements (like Perl for example) then I can usually avoid even this much use of the goto statement, but in C++ this is sometimes the simplest, cleanest solution.

---

<div class="post-metadata">

**Author:** ![ultrafilter](https://avatars.discourse-cdn.com/v4/letter/u/3d9bf3/32.png) [@ultrafilter](https://boards.straightdope.com/u/ultrafilter)\
**Post date:** [July 17, 2005, 7:05pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/46 "2005-07-17T19:05:48Z")

</div>

> [@Orbifold](#):
>
> …but in C++ this is sometimes the simplest, cleanest solution.

For what you’ve shown, having a break and an error flag would have the same effect, and is easier to maintain.

---

<div class="post-metadata">

**Author:** ![Sam\_Stone](https://avatars.discourse-cdn.com/v4/letter/s/ecccb3/32.png) [@Sam\_Stone](https://boards.straightdope.com/u/Sam_Stone)\
**Post date:** [July 17, 2005, 8:25pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/47 "2005-07-17T20:25:35Z")

</div>

One of the problems with hungarian notation is that that variable types tend to NOT be changed consistently when the underlying type changes, and that creates misleading code. This happens a lot with types that are common shorthand. Is wParam always guaranteed to be a word? Nope. But it’s still called wParam.

I prefer code that when read describes the logical structure of the program. The underlying type of the variable is an implementation detail that is better left hidden.

I prefer:

```auto

if (customerName.length > max_size)
  errorText = TOO_LONG;

```

to

```auto

if (lpcstrCustomer.length > nSize)
  lpszrerrText = lpszTOO_LONG;

```

Here’s an example from Charles Simonyi’s article advocating Hungarian in the MSDN knowledgebase:

```auto

   #include "sy.h"
   extern int *rgwDic;
   extern int bsyMac;
   struct SY *PsySz(char sz[])
      {
      char *pch;
      int cch;
      struct SY *psy, *PsyCreate();
      int *pbsy;
      int cwSz;
      unsigned wHash=0;
      pch=sz;
      while (*pch!=0
         wHash=(wHash<>11+*pch++;
      cch=pch-sz;
      pbsy=&rgbsyHash[(wHash&077777)%cwHash];
      for (; *pbsy!=0; pbsy = &psy->bsyNext)
         {
         char *szSy;
         szSy= (psy=(struct SY*)&rgwDic[*pbsy])->sz;
         pch=sz;
         while (*pch==*szSy++)
            {
             if (*pch++==0)
             return (psy);
            }
         }
      cwSz=0;
      if (cch>=2)
         cwSz=(cch-2/sizeof(int)+1;
      *pbsy=(int *)(psy=PsyCreate(cwSY+cwSz))-rgwDic;
      Zero((int *)psy,cwSY);
      bltbyte(sz, psy->sz, cch+1);
      return(psy);
      }

```

Bear in mind that this is an example of GOOD hungarian. I think it sucks. I also hate his indenting style.

---

<div class="post-metadata">

**Author:** ![zega](https://avatars.discourse-cdn.com/v4/letter/z/eada6e/32.png) [@zega](https://boards.straightdope.com/u/zega)\
**Post date:** [July 17, 2005, 9:09pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/48 "2005-07-17T21:09:32Z")

</div>

Having had to decipher a several-page long optimization algorithm that made heavy use of GOTO (in Fortran), I would have to say GOTO is pretty horrible. Enclosed loops are so much easier on the brain, and force you to organize your process. And if your code is going to be used and expanded by others in the future, using GOTO statements can be downright rude and inconsiderate. 🙂

---

<div class="post-metadata">

**Author:** ![Orbifold](https://avatars.discourse-cdn.com/v4/letter/o/779978/32.png) [@Orbifold](https://boards.straightdope.com/u/Orbifold)\
**Post date:** [July 18, 2005, 2:43am UTC](https://boards.straightdope.com/t/i-used-goto/312648/49 "2005-07-18T02:43:20Z")

</div>

> [@ultrafilter](#):
>
> For what you’ve shown, having a break and an error flag would have the same effect, and is easier to maintain.

And what if I have many more loops, both nested and sequential? I would have to check the error flag at the beginning of every loop (well, every loop after the first point where the error could occur), in order to ensure that the error propagates out of the nested loops correctly. What if errors are truly an exceptional case, and 99.9% of the time the error handling code goes unused? And what if this is a heavily-used portion of the code as well? Why should I be inserting “!error &&” at the beginning of _every_ loop to deal with an exceptional condition?

I also don’t see what is hard to maintain about this example. **Sam Stone** has made a good argument about maintaining spaghetti logic, but in his own words:

> [@Sam Stone](#):
>
> In a properly structured program, you can break down chunks of the code and understand what they are doing. This little bit does this. This function achieves that.

My code fragment satisfies this condition nicely. The error-handling code is isolated from the main path of the algorithm, and its position immediately after the main return statement clearly identifies it as code which is only executed in exceptional conditions. Jumps to the error-handling code are also clearly identifiable.

Maintainable? The error-handling code, being isolated, is easy to alter, and new calls to the error-handling code are easy to insert. Moreover, if it becomes necessary to modify some other part of the algorithm that doesn’t use the error-handling code, then that can be accomplished without the new programmer worrying about breaking the error-handling mechanism. Whereas with an error flag and a break statement, any change to the algorithm, anywhere, can break the error-handling mechanism even if the change is to a part of the algorithm that doesn’t use the mechanism, if the programmer forgets to include that all-important “!error &&”.

As I said, if C++ had labelled loops and labelled break statements like Perl then that would be a better solution than mine; likewise if I don’t mind the overhead of structured exception handling (if I’m already using it somewhere else, for example) then that would be a better solution too. But this solution is low-overhead, clear, and encapsulates the error-handling code nicely.

---

<div class="post-metadata">

**Author:** ![Sam\_Stone](https://avatars.discourse-cdn.com/v4/letter/s/ecccb3/32.png) [@Sam\_Stone](https://boards.straightdope.com/u/Sam_Stone)\
**Post date:** [July 18, 2005, 4:14am UTC](https://boards.straightdope.com/t/i-used-goto/312648/50 "2005-07-18T04:14:34Z")

</div>

Orbifold: i think your example is reasonable. Visual Basic’s ON ERROR GOTO does the same thing. A try/catch block as well.

---

<div class="post-metadata">

**Author:** ![EllisDee](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/ellisdee/32/4531_2.png) [@EllisDee](https://boards.straightdope.com/u/EllisDee)\
**Post date:** [July 18, 2005, 10:07am UTC](https://boards.straightdope.com/t/i-used-goto/312648/51 "2005-07-18T10:07:01Z")

</div>

I use GOTO logic, but without GOTO statements. I just find that it makes the code more readable in certain situations, and also for the reasons **Orbifold** cites. Here’s an example, and I won’t mind if somebody tears it apart for the sheer number of coding standard violations, as I think I have more violations than lines of code. Still, to my mind, this code is compact and easy to maintain:

```auto

Private Function CheckDirty() As Boolean
  Dim i As Long

  CheckDirty = True
  Do While CheckDirty
    i = lstEmployee.ItemData(.lstEmployee.ListIndex)
    If StrComp(txtFirst.Text, mEmp(i).First, vbBinaryCompare) <> 0 Then Exit Do
    If StrComp(txtLast.Text, mEmp(i).Last, vbBinaryCompare) <> 0 Then Exit Do
    If mEmp(i).Support <> (chkSupport.Value = 1) Then Exit Do
    If mEmp(i).Train <> (chkTrain.Value = 1) Then Exit Do
    If mEmp(i).Setup <> (chkSetup.Value = 1) Then Exit Do
    If mEmp(i).Teardown <> (chkTeardown.Value = 1) Then Exit Do
    If Val(txtLaptops.Text) <> mEmp(i).Laptops Then Exit Do
    CheckDirty = False
  Loop
  If mblnDirty <> CheckDirty Then
    mblnDirty = CheckDirty
    EnableToolbar
  End If
End Function

```

This example is blatant GOTO logic, though there are no GOTO statements in it. What say you on how easy/difficult this code (and others examples of its ilk) would be to maintain?

---

<div class="post-metadata">

**Author:** ![Sage\_Rat](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/sage_rat/32/399_2.png) [@Sage\_Rat](https://boards.straightdope.com/u/Sage_Rat)\
**Post date:** [July 18, 2005, 4:38pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/52 "2005-07-18T16:38:12Z")

</div>

> [@Ellis Dee](#):
>
> I use GOTO logic, but without GOTO statements. I just find that it makes the code more readable in certain situations, and also for the reasons **Orbifold** cites. Here’s an example, and I won’t mind if somebody tears it apart for the sheer number of coding standard violations, as I think I have more violations than lines of code. Still, to my mind, this code is compact and easy to maintain:

I’ve seen (Java) code that worked like that, that was hideous. Yours is small enough and only does one thing per line so it doesn’t matter. BUT, the sucker I had to deal with was a full ass honking game written into a single do {} while about 5000 lines long that got looped over, and any time he felt like he was done, he would just go “break;”. ERGGGHHHHHHH NO DO THAT!!!

```auto

while (game) {
   do {
      drawBackground();

      if (status == 1) {
         drawMenu();
         break;
      }
      else if (status == 2) {
         drawMap();
      }

      updatePositions();

      if (status != 3) {
         moveCar();
         break;
      }
   }
   while (0);
}

```

NWOOOOOOOOOOO!!!

No comments either, nor functions–unlike in the example above, which does have functions. He just copied and pasted the same code in three or four times as needed in various random places.

---

<div class="post-metadata">

**Author:** ![wolf\_meister](https://sea3.discourse-cdn.com/straightdope/user_avatar/boards.straightdope.com/wolf_meister/32/15202_2.png) [@wolf\_meister](https://boards.straightdope.com/u/wolf_meister)\
**Post date:** [July 18, 2005, 6:03pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/53 "2005-07-18T18:03:09Z")

</div>

I’m a big fan of GOTO and as others have stated, I cannot see the hatred for it.  
Maybe the reason for its strict prohibition, is that it is easily enforceable.  
“Hey, you used a GOTO in this program. Don’t do that !!”

I am also a firm believer in **comments** in programs. But unlike using GOTO, criticizing inadequate commenting styles is somewhat tougher to do.  
“Hey, you know the rules - 1 line of comments for every fifty lines of code.”

Incidentally, JavaScript has eschewed the GOTO command entirely. Which other programming languages have adopted this unseemly practice?

---

<div class="post-metadata">

**Author:** ![Rysto](https://avatars.discourse-cdn.com/v4/letter/r/ecccb3/32.png) [@Rysto](https://boards.straightdope.com/u/Rysto)\
**Post date:** [July 18, 2005, 6:58pm UTC](https://boards.straightdope.com/t/i-used-goto/312648/54 "2005-07-18T18:58:20Z")

</div>

Java doesn’t have goto, but it does have labelled breaks and exceptions, which handle most situations where you’d want a goto.

---

<div class="post-metadata">

**Author:** ![Small\_Clanger](https://avatars.discourse-cdn.com/v4/letter/s/9fc348/32.png) [@Small\_Clanger](https://boards.straightdope.com/u/Small_Clanger)\
**Post date:** [July 19, 2005, 8:45am UTC](https://boards.straightdope.com/t/i-used-goto/312648/55 "2005-07-19T08:45:25Z")

</div>

> [@laina\_f](#):
>
> Your grade:  
> Consistency of style: F  
> Maintainability: D  
> Efficiency: F  
> Elegance: F  
> Impressing anyone who’s been coding for more than a couple of weeks: F

This for my benefit?

FWIW - the real code looks more like one of **Sam Stone** ’s _good_ examples (the one with a stream of boolean variable checks) than the pseudo code I’ve posted.

> [@](#):
>
> I have, however, enjoyed the geek fest.

Phew. I didn’t really intend this as a code review y’know.

[Previous page](https://boards.straightdope.com/t/i-used-goto/312648.md?page=2)
