Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - longjmp()

C library function - longjmp()

C Standard Library - <setjmp.h> C Standard Library -

Description

C Library Function void longjmp(jmp_buf environment, int value) Restores the environment saved by the most recent call to the setjmp() macro, and thejmp_buf parameters are set by a previous call to setjmp().

longjmp() is a function in the C standard library a function in the C standard library used to perform non-local jumps. It allows a program to jump between multiple stack frames, and is typically used for error handling or exception handling, as well as for changing control flow in certain specific situations.

Declaration

Here is the declaration of the longjmp() function.



#include 



void longjmp(jmp_buf env, int val);

Parameters

Return Value

The longjmp() function itself has no return value, but it jumps the program's control flow back to the point where setjmp() was previously called and passes val as the return value of setjmp().

Example

The following example demonstrates the use of the longjmp() function.

Example

#include

#include

static

jmp_buf buf

;

void

second

(

void

)

{

   

printf

(

"second\n"

)

;

       

// Print

   

longjmp

(

buf

,

1

)

;

           

// Jump back to the setjmp call site - causing setjmp to return 1

}

void

first

(

void

)

{

    second

(

)

;

   

printf

(

"first\n"

)

;

         

// This line can never be reached

}

int

main

(

)

{

 

   

if

(

!

setjmp

(

buf

)

)

{

        first

(

)

;

               

// Before reaching this line, setjmp returns 0

   

}

else

{

                   

// When longjmp jumps back, setjmp returns 1, so this line is entered

       

printf

(

"main\n"

)

;

     

// Print

   

}

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:



second

main

Notes

Use Cases

Summary

longjmp() and setjmp() They provide a very flexible mechanism for jumping between different parts of a program, but using them requires great care to avoid potential problems and undefined behavior. They are commonly used for error handling and exception handling, as well as for changing control flow in certain specific situations.

C Standard Library - <setjmp.h> C Standard Library -