Learn C
#include "advanced/setjmp.h"

Non-Local Jumps with setjmp/longjmp in C

#concept

setjmp/longjmp (<setjmp.h>) jump across function boundaries: setjmp(env) snapshots the execution context returning 0, and a later longjmp(env, code) from anywhere down the call chain rewinds straight back, with setjmp then returning code. It is exception handling without exceptions β€” unwinding deep parsers and aborting doomed computations in one leap.

The price is steep: no destructors run (C has none, but buffered I/O and locks still need care), locals modified between setjmp and longjmp need volatile, and jumping upward past returned functions is undefined. Use for parser bailouts and error escapes, never as a general goto.

#how it works
1

Snapshot with setjmp

if (setjmp(env) == 0) { risky(); } else { recover(); } β€” first pass runs the attempt, longjmp arrivals take the else.

2

Leap with longjmp

longjmp(env, 42); unwinds to the snapshot instantly, making setjmp return 42 β€” depth-independent escape.

3

Volatile shared state

Locals changed between snapshot and leap must be volatile, or their values after return are indeterminate.

4

Cleanup stays manual

No unwinding protocol frees resources β€” release (or design around) everything the leap abandons.

#example
#include <stdio.h>
#include <setjmp.h>
Β 
jmp_buf here;
Β 
void deep(void) {
longjmp(here, 7);
}
Β 
int main(void) {
int code = setjmp(here);
if (code == 0) {
deep();
}
printf("landed %d\n", code);
return 0;
}
Output
landed 7
1setjmp snapshots context into here and returns 0 β€” the attempt branch calls deep().
2deep() longjmps with code 7, rewinding the stack straight back to the snapshot point.
3Execution resumes after setjmp returning 7 β€” landed 7 prints from the recovery path.
#use cases
Bailing out of deep recursive parsers on first fatal error
Test harnesses recovering from crashing test cases
Volatile-qualified state shared across the leap
Preferring error codes where the leap would abandon resources

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.