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

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.