Non-Local Jumps with setjmp/longjmp in C
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.
Snapshot with setjmp
if (setjmp(env) == 0) { risky(); } else { recover(); } β first pass runs the attempt, longjmp arrivals take the else.
Leap with longjmp
longjmp(env, 42); unwinds to the snapshot instantly, making setjmp return 42 β depth-independent escape.
Volatile shared state
Locals changed between snapshot and leap must be volatile, or their values after return are indeterminate.
Cleanup stays manual
No unwinding protocol frees resources β release (or design around) everything the leap abandons.
#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;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself β building beats watching.