The goto statement in C
The goto statement moves the execution of the program to another statement. The transfer of the control is unconditional and one-way.
Advertise on this site. I promise you will like the rates :)
Syntax and rules
The label :
- Must be defined within a function
- Each label in one function must have a unique name. It cannot be a reserved C word.
- C has a separate namespaces for identifiers and labels, so you can use the same name for a variable and a label.
- Must be followed by a statement. We call it a “labeled statement”.
- Has function scope. Therefore the label:
- must have a unique name within that function.
- is not accessible outside the function, where it was defined.
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.
"some statement to be executed"
Examples, using the goto statement
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)
printf("%2d ", row + column);
int i = 0;
printf("i = %d\n", i);
if(i >= 10)
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.
Previous keyword: for
Next keyword: if