C Language | Flow Control | goto Statement
This article introduces the goto statement, which unconditionally jumps to a specified statement.
Unconditional Jumps
The branches and loops introduced so far use conditions to control program flow. You can also move execution directly to a specified location without a condition. Use a goto statement for an unconditional jump.
goto Statement
goto label;
The label identifies the statement to jump to. Labels were briefly introduced in the article about switch statements. Put simply, a label is an identifier attached to a statement. Once a statement has a label, a goto statement can jump to that location. Declare a label as follows.
Label Declaration
label: statement
Label names follow the same naming rules as variables. A goto statement can freely change the flow of a program by jumping to a labeled statement. However, it can jump only within the same function. It cannot jump directly to a statement in another function.
Code 1
#include <stdio.h>
int main() {
int iCount = 0;
LOOP:
printf("counter = %d\n" , iCount);
iCount++;
if (iCount < 10) goto LOOP;
return 0;
}
This program implements a loop with a goto statement. If iCount is less than 10, execution returns to the LOOP label. Otherwise, the program ends.
In places where a for or while statement can be used, use one of those loop statements instead of goto. In most cases, control statements such as if and for are sufficient. Excessive use of goto makes program flow difficult to understand and maintain, so avoid it as a general rule.
A goto statement can still be effective for an algorithm that becomes clearer when written with a jump or when leaving several levels of nested control statements at once. For example, break exits only one level of a nested loop. A goto statement can jump out of every nested loop.
for(;;) {
for(;;) {
...
if(error) goto ERROR;
}
}
ERROR: ...
This is useful when an error occurs inside nested loops and execution must move directly to an outer error-handling section.