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

When to Use goto (Rarely)

 Use Case Why
Exiting multiple nested loopsCleaner than using multiple flags
Jumping to error handling sectionUsed in some legacy C systems

When NOT to Use goto

Poor Practice Reason
Jumping across large code blocksReduces readability
Skipping initialization or cleanupMay lead to bugs or memory leaks
Overusing in modern codeBetter alternatives exist (loops, functions)

Best Practices

PracticeReason
Use meaningful label namesImproves clarity
Minimize goto usageMakes the code cleaner and structured
Replace goto with loops/functionsEncourages structured programming