longjmp() Function Example in C Programming

In this source code example, we will see how to use the longjmp() function in C programming with an example.

longjmp() Function Overview

The longjmp() function is found in the <setjmp.h> header and is designed to jump back to the program state saved by a prior call to setjmp(). This offers a way to implement non-local jumps and rudimentary exception handling in C, though its use can make the code harder to follow. 

Key Points: 

- The function requires the <setjmp.h> header. 

- It's used alongside setjmp(), which saves the current state of a program. 

- longjmp() is called with two arguments: the jmp_buf where the state is saved and an integer value. This value (if non-zero) is returned by setjmp()

- Proper care is needed when using longjmp() to ensure resources (like dynamically allocated memory) are appropriately managed.

Source Code Example

#include <stdio.h>
#include <setjmp.h>  // Required for setjmp() and longjmp()

jmp_buf jumpBuffer;

void triggerError() {
    printf("An error occurred!\n");
    longjmp(jumpBuffer, 2);  // Jump back to the saved state with a return value of 2
}

int main() {
    int returnValue = setjmp(jumpBuffer);

    if (returnValue != 0) {
        printf("Returned to main() with value: %d\n", returnValue);
        return 1;
    } else {
        printf("Normal execution...\n");
    }

    // Simulate an error scenario
    triggerError();

    printf("This line is not executed.\n");
    return 0;
}

Output

Normal execution...
An error occurred!
Returned to main() with value: 2

Explanation

1. The program begins by including the essential headers: stdio.h for I/O operations and setjmp.h for setjmp() and longjmp().

2. A jmp_buf variable, jumpBuffer, is declared globally. This variable will hold the saved state.

3. The triggerError() function prints an error message and then calls longjmp(), passing the saved state and an integer value of 2.

4. Inside main(), the program state is saved using setjmp(jumpBuffer). Initially, setjmp() returns 0.

5. In the normal flow of the program, the "Normal execution..." message is printed.

6. The triggerError() function is called, which results in the longjmp(jumpBuffer, 2) call. The program then jumps back to the setjmp() location.

7. This time, setjmp() returns the value passed to longjmp(), which is 2. This leads to printing "Returned to main() with value: 2".

8. The final message "This line is not executed." is indeed not printed, as the program flow jumps over it due to the longjmp().

The longjmp() function provides a way to jump out of the current execution context and return to a previously saved state. It's a powerful tool but should be used judiciously to maintain clarity and predictability in your code.


Comments