longjmp POSIX Manual

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.

Synopsis

#include <setjmp.h>
void longjmp(jmp_buf env, int val);

The header <setjmp.h> is required for using setjmp and longjmp.

Description

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.

Usage

  1. Call setjmp to save the current execution context in a jmp_buf variable.
  2. Perform operations that might encounter an error.
  3. If an error occurs, call longjmp with the saved jmp_buf to jump back to the setjmp call.

Example

#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;
}

Return Behavior

The setjmp function returns twice:

Considerations

Related Functions