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 */
     }
}

C also has goto. A jump to a label after the loops leaves both of them at once. The label has to be in the same function.

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

Often a return is the clearer way to leave the function. goto is unstructured in the sense used by structured-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); /* free(NULL) is defined. Safe when malloc failed. */
 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