Loading, please wait...

Goto statement

Although it is well known that there is no need to use jumps or gotos in a well-structured program, every language has some form of goto instruction, and C is no exception.

The general format is:

goto label;

........

label: statement;

goto here;

........

here: x=y;

The label is any alphanumeric name in the same form as variable or function names. Restriction: it is possible to have a goto from within a set of {} to a label either inside or outside the same {}, but:

it is NOT possible to have a goto outside a set of {} to a label inside

the {}. It follows that it is NOT possible to go to a label inside a different function!

 

Use of the goto statement:

  1. It is a well-known rule that gotos are a bad thing and should be avoided.
  2. Indeed, the use of a goto is usually an indication of poorly planned and badly structured code. There are, however, valid uses of a goto! In general, a goto should be used if the alternative is to produce much more complicated code to avoid the goto.
  3. An example may be a panic exit out of the deeply nested loop and if blocks, where the alternative may be to set up a series of flags that need to be tested at the exit to each block.
  4. Beware of making excuses for using a goto .!!