ILE C/C++ Run-Time Library Functions


setjmp() -- Preserve Environment

Format

#include <setjmp.h>
int setjmp(jmp_buf env);

Language Level: ANSI

Threadsafe: Yes.

Description

The setjmp() function saves a stack environment that can subsequently be restored by the longjmp() function. The setjmp() and longjmp() functions provide a way to perform a non-local goto. They are often used in signal handlers.

A call to the setjmp() function causes it to save the current stack environment in env. A subsequent call to the longjmp() function restores the saved environment and returns control to a point corresponding to the setjmp() call. The values of all variables (except register variables) available to the function receiving control contain the values they had when the longjmp() function was called. The values of register variables are unpredictable. Nonvolatile auto variables that are changed between calls to the setjmp() function and the longjmp() function are also unpredictable.

Return Value

The setjmp() function returns the value 0 after saving the stack environment. If the setjmp() function returns as a result of a longjmp() call, it returns the value argument of the longjmp() function, or 1 if the value argument of the longjmp() function is 0. There is no error return value.

Example that uses setjmp()

This example stores the stack environment at the statement if(setjmp(mark) != 0) ...

When the system first performs the if statement, it saves the environment in mark and sets the condition to FALSE because setjmp()returns a 0 when it saves the environment. The program prints the message:


setjmp has been called

The subsequent call to function p tests for a local error condition, which can cause it to perform the longjmp() function. Then, control returns to the original function using the environment that is saved in mark. This time, the condition is TRUE because -1 is the return value from the longjmp() function. The program then performs the statements in the block and prints:


setjmp has been called

Then the program calls the recover() function and exits.

#include <stdio.h>
#include <setjmp.h>
 
jmp_buf mark;
 
void p(void);
void recover(void);
 
int main(void)
{
   if (setjmp(mark) != 0)
   {
      printf("longjmp has been called\n");
      recover();
   }
   printf("setjmp has been called\n");
   p();
   exit(1);
}
 
void p(void)
{
 
      longjmp(mark, -1);
}
 
void recover(void)
{
exit(1);
}

Related Information


[ Top of Page | Previous Page | Next Page | Table of Contents | Index ]