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.
if (problem) goto fail; /* ... */ return 0; fail: /* cleanup */ return -1;
Try it
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.
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
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
setjmpandlongjmp. - Declare, then jump. Put variables that the cleanup code uses at the top of the function and initialize them to
NULLor0, so the cleanup block works from any jump point. free(NULL)andfcloseguards. The cleanup pattern relies onfree(NULL)doing nothing; guardfclosewithif (fp).- Avoid backward jumps that imitate loops; use
whileorforinstead. - Keep labels few and descriptive:
cleanup,fail,done,out. Use one exit block per function if possible. - Alternatives: early
returnis fine when there is nothing to release; a helper function withreturnleaves nested loops without a label. - Compile-time check: GCC warns with
-Wjump-misses-init(part of-Wc++-compat) about jumps over initializations.