The goto keyword causes program execution to jump to the label specified in the goto statement. The general form of goto is
goto label; . . . label:
All labels must end in a colon and must not conflict with keywords or function names. Furthermore, a goto can branch only within the current function—not from one function to another.
| Programming Tip |
Although the goto fell out of favor decades ago as a preferred method of program control, it does occasionally have its uses. One of them is as a means of exiting from a deeply nested routine. For example, consider this fragment: int i, j, k;
int stop = 0;
for(i=0; i<100 && !stop; i++) {
for(j=0; j<10 && !stop; j++) {
for(k=0; k<20; k++) {
// ...
if(something()) {
stop = 1;
break;
}
}
}
}
As you can see, the variable stop is used to cancel the two outer loops if some program event occurs. However, a better way to accomplish this is shown below, using a goto: int i, j, k;
for(i=0; i<100; i++) {
for(j=0; j<10; j++) {
for(k=0; k<20; k++) {
// ...
if(k+4 == j + i) {
goto done;
}
}
}
}
done: // ...
As you can see, the use of the goto eliminates the extra overhead that was added by the repeated testing of stop in the previous version. Although the goto as a general-purpose form of loop control should be avoided, it can occasionally be employed with great success. |