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

C Library Macros – setjmp()

C Library Macros - setjmp()

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

setjmp() is a function in the C standard library a macro used to save the current program execution state, so that it can later be restored via longjmp() that saved state.

C Library Macros int setjmp(jmp_buf environment) : creates and initializes a local jmp_buf buffer for later jumping back to. This subroutine saves the program's calling environment in the buffer pointed to by the env argument, which will be used by longjmp. If returning from a direct call to setjmp, the return value is 0. If returning from a restored calling environment via longjmp, setjmp returns a nonzero value.

Declaration

The following is the declaration of the setjmp() macro.



#include 



int setjmp(jmp_buf env);

Parameters

Return Value

Example

The following example demonstrates the use of the setjmp() macro.

Example

#include

<

stdio.h

#include

<

setjmp.h

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

Use Cases

Notes

Summary

setjmp() and longjmp() provides a very flexible mechanism for jumping between different parts of a program. Although they are useful for changing control flow in certain specific situations, they must be used with care in practice to avoid potential problems and undefined behavior.

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