C Library Macro -setjmp()

C Standard Library - <setjmp.h>

setjmp()is the C standard library<setjmp.h>A macro used to save the current program execution state so that at some later time it can belongjmp()to return to that state.

C Library Macroint setjmp(jmp_buf environment): Creates a local jmp_buf buffer and initializes it for future jumps back to this point. This subroutine saves the program's calling environment in the buffer pointed to by the env parameter, and env will be used by longjmp. If it returns from a direct call to setjmp, setjmp returns 0. If it returns from a program calling environment restored by longjmp, setjmp returns a nonzero value.

Declaration

Below is the declaration of the setjmp() macro.

#include <setjmp.h>

int setjmp(jmp_buf env);

Parameter

  • env: onejmp_bufA variable of this type, used to save the current program execution state.

Return Value

  • ifsetjmp()When called directly, the return value is 0.
  • ifsetjmp()is throughlongjmp()What the call returns is thelongjmp()non-zero value set by

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 - making setjmp return 1 } void first(void) { second(); printf("first\n"); // It is impossible to execute this line. } int main() { if ( ! setjmp(buf) ) { first(); // Before entering 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 us compile and run the above program, which will produce the following result:

second
main

Use Case

  • Error handling and exception handling:setjmp()andlongjmp()It can be used to implement simple error and exception handling mechanisms.
  • state machine: In state machine state transitions, sometimes it is necessary to jump between different states,setjmp()andlongjmp()can be used to implement this kind of state transition.
  • used together with signal handling: In some special cases,setjmp()andlongjmp()It can be used to jump out of a signal handler.

Notes

  • Usagesetjmp()andlongjmp()They require great care because they can cause the program's control flow to become very chaotic, resulting in code that is difficult to understand and debug.
  • Avoid using them in environments involving multithreading or signal handlers,setjmp()andlongjmp()because they may lead to undefined behavior.

Summary

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

C Standard Library - <setjmp.h>

other extensions