0
0
CHow-ToBeginner · 3 min read

How to Use goto in C: Syntax, Example, and Common Pitfalls

In C, the goto statement allows you to jump to a labeled statement within the same function. Use goto label; to jump and define the label with label:. It is useful for breaking out of nested loops or error handling but should be used carefully to keep code clear.
📐

Syntax

The goto statement transfers control to a labeled statement within the same function. The label is defined by an identifier followed by a colon.

  • goto label; - jumps to the label.
  • label: - marks the target location.
c
goto label;

// some code

label:
// code to execute after jump
💻

Example

This example shows how goto can jump out of a loop when a condition is met.

c
#include <stdio.h>

int main() {
    int i;
    for (i = 0; i < 5; i++) {
        if (i == 3) {
            goto end_loop;
        }
        printf("i = %d\n", i);
    }

end_loop:
    printf("Loop ended early at i = %d\n", i);
    return 0;
}
Output
i = 0 i = 1 i = 2 Loop ended early at i = 3
⚠️

Common Pitfalls

Using goto can make code hard to read and maintain if overused or used carelessly. Avoid jumping into loops or skipping variable initializations. It is best used for error handling or breaking out of nested loops.

Wrong: Jumping into a block that skips important setup.

Right: Using goto to jump to cleanup code at the end of a function.

c
#include <stdio.h>

int main() {
    int x = 0;

    goto skip_init; // Bad: skips initialization
    x = 5;

skip_init:
    printf("x = %d\n", x); // x is 0, not 5
    return 0;
}
Output
x = 0
📊

Quick Reference

Tips for using goto safely:

  • Use labels only within the same function.
  • Do not jump into loops or skip variable initialization.
  • Prefer goto for error cleanup or breaking nested loops.
  • Keep code readable by limiting goto usage.

Key Takeaways

The goto statement jumps to a labeled statement within the same function.
Define labels with an identifier followed by a colon, e.g., label:.
Use goto carefully to avoid confusing code and maintain readability.
Common uses include breaking out of nested loops and error handling cleanup.
Never jump into blocks that skip important code like variable initialization.