Goto Statement
The goto statement transfers control to a labeled statement in the code.The goto statement is a jump statement which is sometimes also referred to as an unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function.
Goto Statement Syntax
goto label; // Jump to the label
label: // Label definition
// Code to execute
- Explanation
- Label:
- A label is an identifier followed by a colon (
label:
). - It acts as a destination for the
goto
statement.
- A label is an identifier followed by a colon (
- goto Usage:
- Transfers control to the labeled location unconditionally.
- Scope:
- The
goto
and its label must be in the same function.
- The
- Label:
Example:1
#include <stdio.h>
int main() {
int i = 0;
if (i == 0) {
goto label;
}
printf("This will not print.\n");
label:
printf("Jumped to label.\n");
return 0;
}
Output
Jumped to label.
Example 2: goto for Error Handling
#include <stdio.h>
int main() {
int num;
printf("Enter a positive number: ");
scanf("%d", &num);
if (num < 0) {
goto error; // Jump to error handling
}
printf("You entered a positive number: %d\n", num);
return 0;
error:
printf("Error: Negative numbers are not allowed.\n");
return 1;
}
Output
Enter a positive number: -5
Error: Negative numbers are not allowed.