Easy Tutorial
❮ C Function Strftime C Exercise Example94 ❯

C Library Function - longjmp()

C Standard Library - <setjmp.h>

Description

The C library function void longjmp(jmpbuf environment, int value) restores the environment to the state saved by the most recent call to setjmp() macro, with the jmpbuf parameter being set by a previous call to setjmp().

Declaration

Following is the declaration for the longjmp() function.

void longjmp(jmp_buf environment, int value)

Parameters

Return Value

This function does not return any value.

Example

The following example demonstrates the use of the longjmp() function.

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

static jmp_buf buf;

void second(void) {
    printf("second\n");         // Prints
    longjmp(buf,1);             // Jumps back to where setjmp was called - causing setjmp to return 1
}

void first(void) {
    second();
    printf("first\n");          // Will never reach this line
}

int main() {   
    if ( ! setjmp(buf) ) {
        first();                // Enters here before setjmp returns 0
    } else {                    // When longjmp jumps back, setjmp returns 1, thus entering this block
        printf("main\n");       // Prints
    }

    return 0;
}

Let's compile and run the above program, which will produce the following result:

second
main

C Standard Library - <setjmp.h>

❮ C Function Strftime C Exercise Example94 ❯