C longjmp()

The longjmp() function defined in the setjmp.h header file. It helps to restore a stack environment saved previously in 'environment' by the setjmp() macro in the same invocation of the program with the corresponding argument jmp_buf.


void longjmp(jmp_buf environment, int value); #where environment is the object

 

longjmp() Parameters:

The longjmp() function takes two parameters. When longjmp() was called all variables that are available to the function that receives the control over the values they had.

Parameter Description Required / Optional
environment the object of type jmp_buf containing information to restore the environment at the setjmp's call. Required
value the value to which the setjmp expression evaluates Required 

longjmp() Return Value

The longjmp() function does not return any value.

Examples of longjmp() 

Example 1: Working of longjmp() function in C?


#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
int main () {
   int x;
   jmp_buf env;

   x = setjmp( env );
   
   if( x != 0 ) {
      printf("Output from a longjmp() with value as %s\n", x);
      exit(0);
   }
   printf("Function call\n");
   jmpfunction( env );
   
   return(0);
}

void jmpfunction(jmp_buf env) {
   longjmp(env, "Programming");
}

Output:


Function call
Output from a longjmp() with value as Programming

Example 2: How pow() function worked in C?


#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
jmp_buf env;

void output( void )
{
    printf( "About to longjmp\n" );
    longjmp( env, 14 );
}

int main( void )
{
    int value = 293;

    if( 0 == ( value = setjmp( env ) ) ) {
        printf( "After calling %d\n", value );
        rtn();
        printf( "Back from output %d\n", value );
    } else {
        printf( "Back from longjmp %d\n", value );
    }
    
    return EXIT_SUCCESS;
}

Output:


After calling setjmp 0
About to longjmp
Back from longjmp 14