c / expert
Snippet
Non-Local Exception Emulation with setjmp, longjmp, and Volatile Storage
The setjmp and longjmp functions enable non-local jump control flow across function call stacks. Local non-static variables modified between setjmp and longjmp must be marked volatile to guarantee their state is preserved when stack registers are unwound.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>#include <setjmp.h>static jmp_buf env;void error_recovery(void) {volatile int status_code = 404;if (setjmp(env) == 0) {longjmp(env, 1);} else {printf("Recovered error code: %d\n", status_code);}}
Breakdown
1
static jmp_buf env;
Defines register environment storage buffer used to save execution context state.
2
volatile int status_code = 404;
Declares local variable with volatile qualifier to prevent value corruption across longjmp call.
3
if (setjmp(env) == 0)
Saves current execution context; returns 0 during initial call and non-zero upon longjmp return.
4
longjmp(env, 1);
Restores saved stack environment in env, jumping execution back to setjmp evaluation point.