Defined in header <setjmp.h> | ||
---|---|---|
void longjmp( jmp_buf env, int status ); | (until C11) | |
_Noreturn void longjmp( jmp_buf env, int status ); | (since C11) |
Loads the execution context env
saved by a previous call to setjmp
. This function does not return. Control is transferred to the call site of the macro setjmp
that set up env
. That setjmp
then returns the value, passed as the status
.
If the function that called setjmp
has exited (whether by return or by a different longjmp
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 when 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) |
env | - | variable referring to the execution state of the program saved by setjmp |
status | - | the value to return from setjmp . If it is equal to 0 , 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 jump_buffer; noreturn void a(int count) { printf("a(%d) called\n", count); longjmp(jump_buffer, count+1); // will return count+1 out of setjmp } int main(void) { volatile int count = 0; // local vars must be volatile for setjmp if (setjmp(jump_buffer) != 9) a(count++); }
Output:
a(0) called a(1) called a(2) called a(3) called a(4) called a(5) called a(6) called a(7) called a(8) called
saves the context (function macro) |
|
C++ documentation for longjmp |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/c/program/longjmp