From what I understood, setjmp
saves the current context and it's supposed to restore it when calling longjmp
. However the next piece of code prints 15 (I compiled with -g and without any optimization). Did I misunderstand this construct or am I missing anything else?
#include <iostream>
#include <csetjmp>
std::jmp_buf jump_buffer;
int main()
{
int a = 0;
if (setjmp(jump_buffer) == 0) {
a = 15;
std::longjmp(jump_buffer, 42);
}
std::cerr << a << std::endl;
}
Disclaimer: only trying to use it for curiosity. I never heard about this construct until I recently read some paper about NASA coding guidelines that mentioned it's forbidden to use this flow of control construct
Using both c and c++ tags because the code is mixed and I would assume the actual relevant functions are more relevant to c heavy users rather than c++... :/
That's the expected behavior:
Upon return to the scope of setjmp, all accessible objects, floating-point status flags, and other components of the abstract machine have the same values as they had when
std::longjmp
was executed, except for the non-volatile local variables insetjmp
's scope, whose values are indeterminate if they have been changed since thesetjmp
invocation.
The value of a
when executing longjmp
is 15, so that is a value one could expect to see (it's indeterminate in general). The jmp_buf
only stores the point of execution. Not the state of every variable in the program.