The goto statement moves the execution of the program to another statement. The transfer of the control is unconditional and one-way.
The label :
When the code reaches the goto
statement, the control of the program “jumps” to the label. Then the execution continues normally.
If the execution reaches the labeled statement without a jump the program will execute it just like any other.
goto labelName; ... labelName: "some statement to be executed"
Jumping out from nested loop:
void exitFromNestedLoops(int rows, int columns) { int row, column; for(row = 0; row < rows; row++) { for(column = 0; column < columns; column++) { if((row+column) > 20) goto exit; printf("%2d ", row + column); } printf("\n"); } exit: printf("Exit\n"); }
Creating a loop:
void loopUsingGoto() { int i = 0; begin: printf("i = %d\n", i); i++; if(i >= 10) goto end; goto begin; end: printf("quit\n"); }
The above examples are available on GitHub and also as a direct download in this zip file. It contains the source file(main.c) that you can use to run the examples.
Good coding practice:
Any program that uses the goto
statement could and most likely should be redesigned to accomplish the
task without it. You can use break, continue and return instead.
Pretty much all developers consider the use of goto as a bad coding
practice. It ruins the code readability and makes debugging and
understanding the code harder.
For my 12 years experience with different programming languages and technologies, there was only 1 (one) case where I chose to use goto. And that was a very specific situation with script code embedded in a description architecture.
See also: