C goto Statement
In this page:
What is goto?
goto transfers execution directly to a labeled line elsewhere in the same function, bypassing the normal sequential flow of the code entirely, which makes it powerful but also the control-flow tool most likely to make a program's logic hard to follow if used carelessly.
Example: What is goto?
#include <stdio.h>
int main() {
goto skip;
printf("never runs");
skip:
printf("Jumped past the printf");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Syntax and Labels
A label is simply an identifier followed by a colon placed in front of a statement, marking that line as a valid jump target, and it can be positioned anywhere within the same function that a goto elsewhere in that function wants to reach.
Example: Syntax and Labels
#include <stdio.h>
int main() {
int x = 5;
if (x > 0) goto positive;
printf("not positive");
return 0;
positive:
printf("Positive");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Breaking Out of Deep Nesting
When an error condition is detected deep inside several nested loops, a single goto cleanup; can exit all of them in one step, whereas a plain break only escapes the single innermost loop, leaving you to manually break out of each remaining level.
Example: Breaking Out of Deep Nesting
#include <stdio.h>
int main() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
goto cleanup;
}
}
}
cleanup:
printf("Exited both loops");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Backward Jumps
Because goto can jump to a label that appears earlier in the code, it's possible to build a loop by jumping backward to a label — but you must make sure the surrounding condition eventually evaluates false, or that backward jump repeats forever exactly like a runaway while loop.
Example: Backward Jumps
#include <stdio.h>
int main() {
int i = 0;
loopStart:
if (i < 3) {
printf("%d ", i);
i++;
goto loopStart;
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Best Practices with goto
Most C style guides restrict goto to a narrow set of legitimate uses, chiefly escaping deeply nested loops and centralizing cleanup code (like closing several open resources before returning), while steering clear of using it as a general substitute for structured loops and conditionals.
Example: Best Practices with goto
#include <stdio.h>
int main() {
int success = 0;
if (!success) {
goto cleanup;
}
printf("never runs");
cleanup:
printf("Centralized cleanup reached");
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: