Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

<setjmp.h> — non-local jumps

The <setjmp.h> header saves a return point and resumes it from a nested call. It requires strict control over lifetimes and resources.

Version: C23; repository compiler flag, production runtime not attested

Syntax

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

<setjmp.h> provides the array type jmp_buf, the setjmp macro, and the longjmp function. In C23, __STDC_VERSION_SETJMP_H__ is 202311L. The syntax declaration of setjmp is descriptive: do not declare it yourself or suppress its macro.

setjmp(env) saves the calling environment and initially returns 0. longjmp(env, val) resumes that point with result val, replacing 0 with 1; it never returns to its caller.

A bare setjmp call, its logical negation (!), or a relational or equality comparison in which the call is one operand and the other is an integer constant expression must form the entire controlling expression of a selection or iteration statement. Alternatively, the call, optionally cast to void, may form the entire expression of an expression statement. Do not use setjmp as the condition of ?:. Initializing int r = setjmp(env); causes undefined behavior.

The target must remain live in the same thread; never jump into a terminated function or a departed variably modified type's scope. Non-volatile automatic local objects in the target function that changed since the environment was saved have indeterminate representations. The jump skips cleanup code, neither releases resources nor restores file or floating-point environment state.

Examples

#include <setjmp.h>
#include <stdio.h>

static jmp_buf env;

static void fail(void)
{
    longjmp(env, 0);
}

int main(void)
{
    if (setjmp(env) == 0) {
        puts("before");
        fail();
        puts("unreachable");
    } else {
        puts("recovered");
    }
    return 0;
}

Result

before
recovered

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources