Learn C
#include "controlflow/goto.h"

goto & Cleanup Jumps in C

#concept

goto jumps to a same-function label unconditionally — the most powerful and most shunned control statement. Arbitrary backward jumps build spaghetti, but C kept goto respectable through one pattern: forward jumps to shared cleanup code. Acquire several resources, and on any failure goto the single block that releases whatever was obtained.

The Linux kernel uses this idiom pervasively. Rules that keep it safe: jump forward only, jump to cleanup only, never into blocks or over initializations (which the compiler forbids anyway).

#how it works
1

Labels mark targets

cleanup: labels a spot; goto cleanup; jumps there — same function only, never across functions.

2

The cleanup pattern

Open file, allocate buffer, lock — each step's failure jumps to one exit block freeing everything acquired so far.

3

Forward only

Forward jumps to cleanup read as structured exits; backward jumps rebuild loops the language already provides.

4

Compiler guardrails

Jumping into a block's scope or over variable initializations is rejected — the remaining uses are the safe ones.

#example
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
int *buf = malloc(3 * sizeof *buf);
if (!buf) goto fail;
buf[0] = 7;
printf("%d\n", buf[0]);
free(buf);
return 0;
fail:
fprintf(stderr, "out of memory\n");
return 1;
}
Output
7
1malloc either returns usable memory or NULL — the check routes failure to the single fail label.
2Success prints 7 and frees normally; the fail block runs only on the error path.
3One cleanup site serves every failure — the pattern scales as more resources join.
#use cases
Multi-resource functions with one shared cleanup/exit block
Breaking out of deeply nested loops cleanly
Kernel and systems code following the established cleanup idiom
Replacing nested error-if pyramids with flat acquire-then-goto flow

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.