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 goto with 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.