C Library Macros - setjmp()
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
env: ajmp_bufvariable used to save the current program execution state.
Return Value
- If both the
setjmp()when called directly, the return value is 0. - If both the
setjmp()is obtained vialongjmp()returned from a call to longjmp, the return value is set bylongjmp()to a nonzero 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
"
)
;
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
"
)
;
}
return
0
;
}
Let's compile and run the above program, which will produce the following result:
second
main
Use Cases
- Error handling and exception handling:
setjmp()andlongjmp()can be used to implement simple error and exception handling mechanisms. - State machines: in state machine transitions, it is sometimes necessary to jump between different states,
setjmp()andlongjmp()can be used to implement such state transitions. - Used together with signal handling: in some special cases,
setjmp()andlongjmp()can be used to jump out of a signal handler.
Notes
- Use
setjmp()andlongjmp()need to be used with great care, because they can make the program's control flow very confusing, resulting in code that is hard to understand and debug. - avoid using them in environments involving multithreading or signal handlers,
setjmp()andlongjmp()because they may cause undefined behavior.
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 -