This document provides a short manual for the longjmp function, which is used for non-local jumps in C programs. Although part of the C standard library, it is widely used in POSIX-compliant systems.
#include <setjmp.h>
void longjmp(jmp_buf env, int val);
The header <setjmp.h> is required for using setjmp and longjmp.
The longjmp function causes a non-local jump to the location previously saved by setjmp. This mechanism can be used for error handling or recovering from an unexpected situation by jumping back to a known state.
The env parameter is a buffer that holds the environment (execution context) saved by a previous call to setjmp. The val parameter specifies the value that setjmp will return when the jump is performed. If val is 0, then setjmp returns 1 instead.
setjmp to save the current execution context in a jmp_buf variable.longjmp with the saved jmp_buf to jump back to the setjmp call.#include <stdio.h>
#include <setjmp.h>
jmp_buf env;
void error_handler() {
printf("An error occurred! Jumping back...\n");
longjmp(env, 1); // Jump back with return value 1
}
int main(void) {
if (setjmp(env) == 0) {
// Initial call to set the jump point
printf("Setting jump point.\n");
// Operations that might trigger an error
error_handler();
// The following line will not be executed if error_handler calls longjmp
printf("This line will not be executed.\n");
} else {
// Code executed after longjmp
printf("Recovered from error using longjmp.\n");
}
return 0;
}
The setjmp function returns twice:
setjmp is initially called, it returns 0.longjmp is called, control jumps back to the setjmp call, and it returns the value passed as the second argument to longjmp (or 1 if that value is 0).longjmp occurs. Ensure proper resource management.longjmp does not unwind the stack, so care must be taken with memory and resource management.setjmp – Saves the current environment for later use by longjmp.