The goto Statement


Syntax

 goto label_identifier;

Notes

The goto statement causes control of program execution to be unconditionally transferred to the statement identified by label_identifier. The statement thus identified must lie within the scope of the same function as the goto statement.

Example

The following example adds the numbers 0-4.

int j=0;
for (int i=0; i<10; i++)
 {
  if (i==5) goto outside_loop;
  j += i;
 }
 
outside_loop:
 cout << "The sum of the numbers 0-4 is: " << j << "\n";
 
// Loop adds numbers 0 - 4, upon exit i==5, j==10.

Programming Style

If the first language that a programmer encountered was basic then he/she will probably be quite familiar with the goto statement. Early basic code was riddled with goto statements because of the limited program flow control mechanisms and because line number based programming was in vogue in the early days (although structured basic has cured many of the deficiencies in the original language). Code with lots of goto statements is notoriously hard to read and maintain and thus should be avoided. Nevertheless, legitimate uses for the goto statement still exist in today's programming environment.