c / expert
Snippet
Non-Local Jumps with setjmp and longjmp
Non-local jumps allow control flow to bypass normal function call and return sequences across the call stack. Calling `setjmp` saves the current execution state (registers and stack context) into a `jmp_buf` structure and returns 0 initially. Later, invoking `longjmp` restores that saved execution state, making `setjmp` appear to return a second time with the non-zero integer code passed to `longjmp`. This pattern simulates exception handling mechanisms in systems C development.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>#include <setjmp.h>static jmp_buf env;void error_recovery(int code) {printf("Error caught: %d. Unwinding execution stack...\n", code);longjmp(env, code);}void process_data(int value) {if (value < 0) {error_recovery(101);}printf("Processing valid value: %d\n", value);}int main(void) {int status = setjmp(env);if (status == 0) {process_data(42);process_data(-5);} else {printf("Execution restored at main. Error code: %d\n", status);}return 0;}
Breakdown
1
static jmp_buf env;
Allocates buffer memory to store processor context and execution stack environment.
2
int status = setjmp(env);
Saves execution context into env; returns 0 on first call and non-zero value when returning from longjmp.
3
longjmp(env, code);
Restores processor state saved in env, jumping directly back to setjmp invocation site with code as return status.