Using goto to jump out of nested loops

suggest change

Jumping out of nested loops would usually require use of a boolean variable with a check for this variable in the loops. Supposing we are iterating over i and j, it could look like this

size_t i,j;
for (i = 0; i < myValue && !breakout_condition; ++i) {
    for (j = 0; j < mySecondValue && !breakout_condition; ++j) {
        ... /* Do something, maybe modifying breakout_condition */
            /* When breakout_condition == true the loops end */
     }
}

But the C language offers the goto clause, which can be useful in this case. By using it with a label declared after the loops, we can easily break out of the loops.

size_t i,j;
for (i = 0; i < myValue; ++i) {
    for (j = 0; j < mySecondValue; ++j) {
        ...
        if(breakout_condition) 
          goto final;
    }
}
final:

However, often when this need comes up a return could be better used instead. This construct is also considered “unstructured” in structural programming theory.

Another situation where goto might be useful is for jumping to an error-handler:

ptr = malloc(N *  x);
if(!ptr)
  goto out_of_memory;

/* normal processing */
free(ptr);
return SUCCESS;

out_of_memory:
 free(ptr); /* harmless, and necessary if we have further errors */
 return FAILURE;

Use of goto keeps error flow separate from normal program control flow. It is however also considered “unstructured” in the technical sense.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents