Everything
7.4.9 <setjmp.h>

Supports transfer of control between functions.

The following macros are implementation-defined.

Type

Definition Name

Description

Type

(macro)

jmp_buf

Indicates the type name corresponding to a storage area for storing information that enables transfer of control between functions.

Function

setjmp

Saves the execution environment defined by jmp_buf of the currently executing function in the specified storage area.

longjmp

Restores the function execution environment saved by the setjmp function, and transfers control to the program location at which the setjmp function was called.

 

The setjmp function saves the execution environment of the current function. The location in the program that called the setjmp function can subsequently be returned to by calling the longjmp function.

An example of how transfer of control between functions is supported using the setjmp and longjmp functions is shown below.

[Format]

  1    #include <stdio.h>
  2    #include <setjmp.h>
  3    jmp_buf env;
  4    void sub( );
  5    void main( )
  6    {
  7
  8        if (setjmp(env)!=0){
  9            printf("return from longjmp\n");
  10           exit(0);
  11       }
  12           sub( );
  13   }
  14
  15   void sub( )
  16   {
  17       printf("subroutine is running \n");
  18       longjmp(env, 1);
  19   }

 

Explanation:

The setjmp function is called in line 8. At this time, the environment in which the setjmp function was called is saved in jmp_buf type variable env. The return value in this case is 0, and therefore function sub is called next.

The environment saved in variable env is restored by the longjmp function called within function sub. As a result, the program behaves just as if a return had been made from the setjmp function in line 8. However, the return value at this time is 1 specified by the second argument of the longjmp function. As a result, execution proceeds to line 9.