The "goto" statement in C

The "goto" statement is used for loop control in one of the sample exam questions (Question 6). Conditional jumps using "goto"s is fairly uncommon in C, but is used widely in some programming languages, and particularly in assembly or machine language programming.

In the program listing in the sample exam paper, the segment containg the goto loop looks something like this:
loop:
     /* start of a pass through list of items */
      sorted = 1;    /* assume sorted */
      printf("Starting a new pass:\n");

      for (count = 3; count > 0; count--)
      {
         if(item[count] < item[count-1])
         {
            swap(item+count, item+(count-1));
            sorted = 0;  /* was not sorted */
         }
         printf("item[%d] == %d\n", count, item[count]);
      }
      printf("item[%d] == %d\n", count, item[count]);
   if (sorted != 1) {goto loop;}

The goto loop construct uses two elements. The first is a label, which is a line consisting of a unique name followed by a colon (Labels are also used within switch() statements). A label marks a location within a program to which program execution can jump. In the above example, the label is named "loop:". There is also a matching "goto" statement of the form "goto label;" ("goto loop" in the example). Normally the goto statement is executed if some logical test is true.

Most C programmers hardly ever use "goto" statements for flow control, and it is generally considered bad programming practice, except in some very specific circumstanses. All flow control statements in C can, however, be replaced by a set of "goto" statements if desired, and in many cases, the actual machine code generated by the compiler will be implemented using the equivalent of "goto"s.

If you write assembly language programs, you will probably have to use "goto"s for your conditional statements and for loop control. In C, it is never necessary to use a "goto" statement, and in virtually all cases there are better ways to implement flow control. In the case of the above example, a "do {...} while (...); loop would be suitable.

"goto" statements is something of which you should be aware, but I would strongly advise against using them, unless you have a very good reason to do so. There are people who would put this even more strongly.


Back to main page
Author : Keith Halewood / Helge Nareid Current contact: Gorry Fairhurst G.Fairhurst@eng.abdn.ac.uk