C goto Statement – Complete Guide with Examples
The goto statement in C is used to jump to a labeled part of the program. It can transfer control anywhere within the same function, regardless of the normal flow of execution.
Use
gotowith caution—it can make code harder to read and maintain.
Syntax of goto in C
goto label;
// … other code …
label:
// code to execute
Example: Basic goto Usage
#include <stdio.h>
int main() {
int num = 3;
if (num == 3) {
goto skip;
}
printf("This line is skipped.\n");
skip:
printf("Jumped to the label 'skip'.\n");
return 0;
}
Output:
Jumped to the label 'skip'.Example: Using goto to Exit Nested Loops
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
goto exit_loops;
}
printf("i = %d, j = %d\n", i, j);
}
}
exit_loops:
printf("Exited both loops using goto.\n");
return 0;
}
Output:
i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
Exited both loops using goto.When to Use goto (Rarely)
| Use Case | Why |
|---|---|
| Exiting multiple nested loops | Cleaner than using multiple flags |
| Jumping to error handling section | Used in some legacy C systems |
When NOT to Use goto
| Poor Practice | Reason |
|---|---|
| Jumping across large code blocks | Reduces readability |
| Skipping initialization or cleanup | May lead to bugs or memory leaks |
| Overusing in modern code | Better alternatives exist (loops, functions) |
Best Practices
| Practice | Reason |
|---|---|
| Use meaningful label names | Improves clarity |
Minimize goto usage | Makes the code cleaner and structured |
Replace goto with loops/functions | Encourages structured programming |