c / expert
Snippet
Non-Local Jump Stack Unwinding with setjmp and longjmp
In plain C, non-local jumps via setjmp and longjmp allow control flow to bypass intermediate stack frames. Calling setjmp saves the execution environment (stack pointer, instruction pointer, and registers) into a jmp_buf object. When longjmp is subsequently called, execution unwinds directly back to the setjmp call site as if setjmp had returned the value passed to longjmp. This mechanism forms the primitive foundation for custom C exception handling.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>#include <setjmp.h>static jmp_buf exception_env;void do_risky_operation(int count) {if (count < 0) {longjmp(exception_env, 1);}printf("Operation succeeded with count %d\n", count);}int main(void) {if (setjmp(exception_env) == 0) {do_risky_operation(-5);} else {printf("Caught exception: invalid negative count\n");}return 0;}
Breakdown
1
static jmp_buf exception_env;
Declares execution context buffer for non-local stack jump restoration.
2
if (setjmp(exception_env) == 0)
Saves state and returns 0 initially; evaluates to non-zero when returned via longjmp.
3
longjmp(exception_env, 1);
Restores environment stored in buffer and transfers control back to setjmp.