Is using a 'goto' statement bad?

Viewed 26731

After doing some reseach on how to break through a secondary loop

while (true) { // Main Loop
   for (int I = 0; I < 15; I++) { // Secondary loop
       // Do Something
       break; // Break main loop?
   }
}

most people recommended to call the 'goto' function
Looking as the following example:

while (true) { // Main Loop
   for (int I = 0; I < 15; I++) { // Secondary Loop
       // Do Something
       goto ContinueOn; // Breaks the main loop
   }
}
ContinueOn:

However; I have often heard that the 'goto' statement is bad practice. The picture below is perfectly illustrating my point: Series found

So

  • How bad is the goto statement really, and why?
  • Is there a more effective way to break the main loop than using the 'goto' statement?
7 Answers

To add to the other answers here, apart from breaking out of nested loops, one neat use of goto is simple and clean state machines:

goto EntryState;

EntryState:
//do stuff
if (condition) goto State1;
if (otherCondition) goto State2;
goto EntryState;

State1:
//do stuff
if (condition) goto State2;
goto State1;

State2:
//do stuff
if (condition) goto State1;
goto State2;

This is a pretty clean and readable way to do state machines, and on top it's performance friendly for free! While you could do this without goto, it would actually only make your code less readable. Don't avoid goto, just think a bit before using it.

Related