IT lexicon › Programming › setjmp/longjmp

setjmp/longjmp

Programming På svenska → Updated: 2026-11-07

C's mechanism for non-local jumps: setjmp saves the processor state, and a later longjmp returns there through any number of function calls.

setjmp writes the stack pointer, return address and callee-saved registers into a jmp_buf and returns 0. When something further down calls longjmp, the registers are restored and setjmp returns a second time, now with a different value. It is a function that returns twice, and compilers have to recognise it — GCC and LLVM have the returns_twice attribute — so they don't keep values in registers that get clobbered. That is why the standard says local variables modified after setjmp are indeterminate unless they are volatile.

libpng and Lua still use it for error handling. Older GCC built all of C++ exception handling on it (SJLJ), paying a cost at every try. In the middle of C++ code, longjmp skips every destructor on the way, which is rarely what anyone wanted.

← Back to the lexicon