| Program termination | |||||||||||||||||||||
| |||||||||||||||||||||
| Unreachable control flow | |||||||||||||||||||||
(C23) | |||||||||||||||||||||
| Communicating with the environment | |||||||||||||||||||||
| |||||||||||||||||||||
| Memory alignment query | |||||||||||||||||||||
(C23) | |||||||||||||||||||||
| Signals | |||||||||||||||||||||
| Signal types | |||||||||||||||||||||
| Non-local jumps | |||||||||||||||||||||
| |||||||||||||||||||||
| Types | |||||||||||||||||||||
Defined in header <setjmp.h> | ||
void longjmp(jmp_buf env,int status); | (until C11) | |
_Noreturnvoid longjmp(jmp_buf env,int status); | (since C11) (until C23) | |
[[noreturn]]void longjmp(jmp_buf env,int status); | (since C23) | |
Loads the execution contextenv saved by a previous call tosetjmp. This function does not return. Control is transferred to the call site of the macrosetjmp that set upenv. Thatsetjmp then returns the value, passed as thestatus.
If the function that calledsetjmp has exited (whether by return or by a differentlongjmp higher up the stack), the behavior is undefined. In other words, only long jumps up the call stack are allowed.
Jumping across threads (if the function that called | (since C11) |
If whensetjmp was called, aVLA or anothervariably-modified type variable was in scope and control left that scope, On the way up the stack, void g(int n){int a[n];// a may remain allocated h(n);// does not return}void h(int n){int b[n];// b may remain allocated longjmp(buf,2);// might cause a memory leak for h's b and g's a} | (since C99) |
Contents |
| env | - | variable referring to the execution state of the program saved bysetjmp |
| status | - | the value to return fromsetjmp. If it is equal to0,1 is used instead |
(none)
longjmp is intended for handling unexpected error conditions where the function cannot return meaningfully. This is similar to exception handling in other programming languages.
#include <stdio.h>#include <setjmp.h>#include <stdnoreturn.h> jmp_buf my_jump_buffer; noreturnvoid foo(int status){printf("foo(%d) called\n", status); longjmp(my_jump_buffer, status+1);// will return status+1 out of setjmp} int main(void){volatileint count=0;// modified local vars in setjmp scope must be volatileif(setjmp(my_jump_buffer)!=5)// compare against constant in an if foo(++count);}
Output:
foo(1) calledfoo(2) calledfoo(3) calledfoo(4) called
| saves the context (function macro)[edit] | |
C++ documentation forlongjmp | |