Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

The goto statement

Reference for the C goto statement and labels: how jumps work, the cleanup-on-error pattern, leaving nested loops, and what you must never jump over.

goto transfers control unconditionally to a labeled statement in the same function. A label is an identifier followed by a colon. Labels have their own name space, so a label may share a name with a variable or function.

Unstructured jumping makes code hard to follow, which is why goto has a bad reputation. Two uses are widely accepted in C: leaving several nested loops at once, and the single cleanup block at the end of a function that releases resources on every error path.

C
    if (problem) goto fail;
    /* ... */
    return 0;
fail:
    /* cleanup */
    return -1;

Try it

C Cleanup on error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Leaving nested loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
goto identifier ;
identifier : statement
Part Description
identifier Names a label in the same function. Labels have function scope: a label may be used before it appears.
statement The labeled statement. Before C23 it must be a statement, not a declaration (end: ; uses an empty statement).

Errors / undefined behavior: jumping to a nonexistent label is a compile error. Jumping into the scope of a variably modified type (such as a VLA) is a constraint violation. Jumping forward past the initialization of an ordinary variable is allowed, but the variable's value is then indeterminate, so using it is undefined.

Usage notes

  • Never jump out of a function. For that, use setjmp and longjmp.
  • Declare, then jump. Put variables that the cleanup code uses at the top of the function and initialize them to NULL or 0, so the cleanup block works from any jump point.
  • free(NULL) and fclose guards. The cleanup pattern relies on free(NULL) doing nothing; guard fclose with if (fp).
  • Avoid backward jumps that imitate loops; use while or for instead.
  • Keep labels few and descriptive: cleanup, fail, done, out. Use one exit block per function if possible.
  • Alternatives: early return is fine when there is nothing to release; a helper function with return leaves nested loops without a label.
  • Compile-time check: GCC warns with -Wjump-misses-init (part of -Wc++-compat) about jumps over initializations.