C Language: setjmp function
(Prepare for Nonlocal Jump)
In the C Programming Language, the setjmp function stores the current environment in the env variable in preparation for a future call from the longjmp function.
Syntax
The syntax for the setjmp function in the C Language is:
int setjmp(jmp_buf env);
Parameters or Arguments
- env
- The current environment saved for a future longjmp function call.
Returns
The setjmp function returns zero when it is called directly. When it is returning from a call from the longjmp function, the setjmp function will return a nonzero value.
Required Header
In the C Language, the required header for the setjmp function is:
#include <setjmp.h>
Applies To
In the C Language, the setjmp function can be used in the following versions:
- ANSI/ISO 9899-1990
setjmp Example
/* Example using setjmp by TechOnTheNet.com */ #include <stdio.h> #include <setjmp.h> /* Declare a global jmp_buf variable that is available to both func and main */ static jmp_buf env; void func(void) { /* Display a message indicating we are entering func */ printf("Starting func\n"); /* Return to main with a return code of 1 (can be anything except 0) */ longjmp(env, 1); /* Display a message indicating we are leaving func */ printf("Finishing func\n"); /* This will never be executed! */ } int main(int argc, const char * argv[]) { /* Define temporary variables */ int result; /* Display a message indicating we are starting main */ printf("Starting main\n"); /* Save the calling environment, marking where we are in main */ result = setjmp(env); /* If the result is not 0 then we have returned from a call to longjmp */ if (result != 0) { /* Display a message indicating the call to longjmp */ printf("longjmp was called\n"); /* Exit main */ return 0; } /* Call func */ func(); /* Display a message indicating we are leaving main */ printf("Finished main\n"); return 0; }
When compiled and run, this application will output:
Starting main Starting func longjmp was called
Similar Functions
Other C functions that are similar to the setjmp function:
See Also
Other C functions that are noteworthy when dealing with the setjmp function:
Advertisements