C library macro - setjmp()



Description

The C library macro int setjmp(jmp_buf environment), saves the current environment into the variable environment for later use by the function longjmp(). If this macro returns directly from the macro invocation, it returns zero but if it returns from a longjmp() function call, then it returns the value passed to longjmp as a second argument.

Declaration

Following is the declaration for setjmp() macro.

int setjmp(jmp_buf environment)

Parameters

  • environment − This is the object of type jmp_buf where the environment information is stored.

Return Value

This macro may return more than once. First time, on its direct invocation, it always returns zero. When longjmp is called with the information set to the environment, the macro returns again; now it returns the value passed to longjmp as second argument.

Example

The following example shows the usage of setjmp() macro.

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

int main () {
   int val;
   jmp_buf env_buffer;

   /* save calling environment for longjmp */
   val = setjmp( env_buffer );
   
   if( val != 0 ) {
      printf("Returned from a longjmp() with value = %s\n", val);
      exit(0);
   }
   
   printf("Jump function call\n");
   jmpfunction( env_buffer );
   
   return(0);
}

void jmpfunction(jmp_buf env_buf) {
   longjmp(env_buf, "tutorialspoint.com");
}

Let us compile and run the above program, this will produce the following result −

Jump function call
Returned from a longjmp() with value = tutorialspoint.com
setjmp_h.htm
Advertisements