gtpc2m6fC/C++ Language Support User's Guide

setjmp-Preserve Stack Environment

This function saves a stack environment that can then be restored by the longjmp function. The nesting level is also saved to validate a longjmp call. The setjmp and longjmp functions provide a way to perform a nonlocal goto. They are often used in signal handlers.

A call to the setjmp function causes it to save the current stack environment in env. The next call to the longjmp function restores the saved environment and returns control to a point corresponding to the setjmp call. The setjmp and longjmp functions are not restricted to the same dynamic load module (DLM).

Format

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

env
The jmp_buf for saving the current stack and other environment information.

Normal Return

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 longjmp, or the value 1 if the value argument of the longjmp function is equal to 0.

Error Return

None.

Programming Considerations

Examples

This example stores the stack environment at the statement:

if(setjmp(mark) != 0) ...

When the program first performs the if statement, it saves the environment in mark and sets the condition to FALSE because setjmp returns the value 0 when it saves the environment. The program prints the following message: setjmp has been called.

The next call to function p tests for a local error condition, which can cause it to perform the longjmp function. (The function p that performs the setjmp function can be in the same DLM or a separate DLM). Then control returns to the original setjmp function using the environment saved in mark. This time the condition is TRUE because -1 is the returned value from the longjmp function. The program then performs the statements in the block and prints the following: longjmp has been called. Finally, the program calls the recover function and returns.

/* This example shows the effect of having set the stack environment.  */
#include <stdio.h>
#include <setjmp.h>
jmp_buf mark;
void p(void);
void recover(void);
int ADLM(void)
{
   if (setjmp(mark) != 0) {
      printf("longjmp has been called\n");
      recover();
      return(1);
      }
   printf("setjmp has been called\n");

  ·
  ·
  ·
p();
  ·
  ·
  ·
return(32); /* Return suitable value */ } void p(void) { int error = 0;
  ·
  ·
  ·
error = 9;
  ·
  ·
  ·
if (error != 0) longjmp(mark, -1);
  ·
  ·
  ·
} void recover(void) {
  ·
  ·
  ·
}

Related Information

longjmp-Restore Stack Environment.