setjmp() Function Example in C Programming

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

setjmp() Function Overview

The setjmp() function, found in the <setjmp.h> header, provides a mechanism to jump back to a certain point in a program, bypassing the normal call and return discipline. It works in tandem with the longjmp() function. This capability can be useful for handling errors and exceptions in C. 

Key Points: 

- Requires the <setjmp.h> header. - setjmp() saves the current state of a program in a jmp_buf type variable. 

- If longjmp() is later called with the saved jmp_buf, the program will return to where setjmp() was set.

- The value passed to longjmp() (other than zero) will be returned by setjmp()

- Can be used for error handling, though it's a more primitive mechanism than exceptions in languages like C++ or Java.

Source Code Example

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

jmp_buf jumpBuffer;

void throwException() {
    longjmp(jumpBuffer, 1);  // Jump back to where setjmp was set
}

int main() {
    if (setjmp(jumpBuffer) != 0) {
        printf("Exception caught!\n");
        return 1;
    } else {
        printf("Executing code...\n");
    }

    // Some hypothetical condition that causes an exception
    throwException();

    printf("This will not be printed.\n");
    return 0;
}

Output

Executing code...
Exception caught!

Explanation

1. The necessary header files, stdio.h for input/output and setjmp.h for setjmp() and longjmp(), are included.

2. A global jmp_buf variable named jumpBuffer is defined. This will hold the information about where to jump back to.

3. The throwException() function demonstrates how longjmp() can be used to jump back to the saved point in setjmp().

4. In the main() function, setjmp() saves the current state in jumpBuffer.

5. When setjmp() is first called, it returns 0, causing the "Executing code..." message to be printed.

6. The throwException() function is then called, which uses longjmp() to jump back to the point where setjmp() saved the state.

7. This time, setjmp() returns the value passed to longjmp(), which is 1. This leads to the "Exception caught!" message being printed.

8. The message "This will not be printed." will never be displayed because the longjmp() call bypasses it.

The setjmp() and longjmp() mechanism provides a rudimentary way to handle unexpected conditions and exceptions in C. However, it's crucial to be cautious when using them since they can make code harder to understand and maintain if overused or misused.


Comments