Is using a ‘goto’ statement bad?

EDIT:

How bad is the goto statement really, and why?

It depends on the exact situation. I can’t remember any time where I found it made the code more readable than refactoring. It also depends on your personal view of readability – some people dislike it more than others, as is clear from the other answers. (As a point of interest, it’s widely used in generated code – all of the async/await code in C# 5 is based on effectively a lot of gotos).

The problem is that situations where goto tends to be used tend to be the kind of situations where refactoring aids things anyway – whereas goto sticks with a solution which becomes harder to follow as the code gets more complicated.

Is there a more effective way to break the main loop than using the ‘goto’ statement?

Absolutely. Extract your method out into a separate function:

while (ProcessValues(...))
{
    // Body left deliberately empty
}

...

private bool ProcessValues()
{
   for (int i = 0; i < 15; i++)
   {
       // Do something
       return false;
   }
   return true;
}

I generally prefer doing this over introducing an extra local variable to keep track of “have I finished” – although that will work too, of course.

Leave a Comment