Home > Articles > Programming > C#

  • Print
  • + Share This
From the author of

From the author of

goto Statements

The goto statement allows unconditional branching to another program section. The form of the goto statement is as follows:

  goto label;

The destination is marked by a label. Legal destinations include the current level of the goto statement or outside of the current loop.

For C++ Programmers

C++ goto statements can transfer control to anywhere in a program. C# goto statements must always jump at the same level or higher out of its enclosing block.

For Java Programmers

Java does not have a goto statement. In C#, the goto statement has restrictions that make it similar to a Java labeled break statement.

The following code shows how a goto statement could be used.

do {
 // some processing
 while (/* some Boolean condition */)
 {
  // some processing
  for (int i=0; i < someValue; i++)
  {
   if (/* some Boolean condition */)
   {
    goto quickExit;
   }
  }
 }
} while (/* some Boolean condition */);

quickExit:

This example displays a potential scenario where the code is deeply nested in processing. If a certain condition causes the end of processing to occur in the middle of that loop, the program has to make several less than graceful checks to get out. The example shows how using a goto might be helpful in making a clean exit from a tricky situation. It may even make the code easier to read, instead of trying to design a clumsy workaround. Again, the decision to use a goto is based on the requirements that a project needs to meet.

A goto may never jump into a loop. Here's an example that should help you visualize just how illogical such an attempt might be.

// error
while (/* some Boolean condition */)
{
 // some processing
 innerLoop:
 // more processing
}

goto innerLoop;

It's normally desirable to have some type of initialization and control while executing a loop. This scenario could easily violate the integrity of any loop, which is why it is not allowed.

NOTE

Much has been said about the value of the goto statement in computer programming. Arguments range from recommending that it be eliminated to using it as an essential tool to get out of a hard spot. Although many people have been able to program without the goto for years, there's always the possibility that someone may still find it necessary. Just be careful with its use and make sure that programs are maintainable.

  • + Share This
  • 🔖 Save To Your Account