The setjmp function is used to save information required by longjmp.

Th setjmp function saves the ate of the current execution environment in a structure of type jmp_buf. This information is used to determine the target for the jump, when the functon longjmp is called.

The return value of setjmp is integer, and determines what is hapenning with the environment. If the return value is zero, then this is the first time that the function is called. If the return value is non-zero, then the function is being called in response to a longjmp, so this is the second time the instruction is being executed. This signs that some condition triggered the longjmp corresponding to this environment variable.

The following code shows an example of setjmp in use:

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

jmp_buf env;

void another_func()
        printf("in another function\n");
        longjmp(env, 0);
        printf("this will never be printed\n");

int main()
        int res = setjmp(env);
        if (res == 0) {
                printf("this is the first time here\n");
        } else {
                printf("this is the second time here\n");
        return 0;
Article created on 2008-08-19 22:11:20

Post a comment