The goto statement allows a program to jump directly to a labeled statement within the same function. It is mainly used for error handling or exiting deeply nested loops, but excessive use can make code difficult to read and maintain.
- Transfers program control to a specified label within the same function.
- Best used for error handling or breaking out of multiple nested loops; avoid unnecessary use.
#include <stdio.h>
int main() {
int n = 0;
// If the number is zero, jump to
// jump_here label
if (n == 0)
goto jump_here;
// This will be skipped
printf("You entered: %d\n", n);
jump_here:
printf("Exiting the program.\n");
return 0;
}
Output
Exiting the program.
Explanation
- If num is 0, the goto statement transfers control directly to the jump_here label, skipping the remaining statements.
- If num is non-zero, the program prints its value normally, demonstrating how goto changes the program's execution flow.
Syntax
goto label;
/* Statements */
label:
// Code to execute
Flowchart of goto

The goto statement allows for jumping to specific parts of a program and understanding its function is still valuable.
Examples of goto
Below are some examples of how to use a goto statement.
Check Even or Odd Number
#include <stdio.h>
int main() {
int n = 26;
if (n % 2 == 0)
// jump to even
goto even;
else
// Jump to odd
goto odd;
even:
printf("%d is even", n);
return 0;
odd:
printf("%d is odd", n);
return 0;
}
Output
26 is even
Prints numbers from 1 to 10
#include <stdio.h>
int main(){
int n = 1;
// Label here
label:
printf("%d ", n);
n++;
if (n <= 10)
// jumb back to the label
goto label;
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
Explanation
- The program uses the goto statement to repeatedly jump back to the labeled statement, printing numbers from 1 to 10.
- After each iteration, n is incremented, and the loop continues until n becomes greater than 10, after which the program terminates.
Jumping Out of a Nested Loop
#include <stdio.h>
int main() {
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (i == 2 && j == 2) {
// Break out of both loops
goto exit_loops;
}
printf("%d %d\n", i, j);
}
}
exit_loops:
printf("Exited loop");
return 0;
}
Output
0 0 0 1 0 2 0 3 0 4 1 0 1 1 1 2 1 3 1 4 2 0 2 1 Exited loop
Explanation
- When i == 2 and j == 2, the goto statement immediately exits both the inner and outer loops by jumping to the specified label.
- This avoids using multiple break statements or extra flag variables, making it easier to exit nested loops.
Error Handling Using goto
#include <stdio.h>
int main() {
int num = -1;
// Check if num is -1
if (num == -1) {
// Jump to error handling
goto error;
}
printf("Valid input: %d\n", num);
return 0;
error:
printf("Error: Invalid input detected.\n");
return -1;
}
Output
Error: Invalid input detected.
Explanation: goto is used to jump to the error label when an invalid input (e.g., -1) is entered. This allows for centralized error handling.