C library macro - setjmp()

Advertisements


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 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. A first time, on its direct invocation, it always returns zero. When longjmp is called with the information set to 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


Advertisements
Advertisements