Why isn't setjmp saving the stack?
Consider the following code:
#include <iostream>
jmp_buf Buf;
jmp_buf Buf2;
void MyFunction()
{
for(int i = 0; i < 5; i++)
{
std::cout << i << std::endl;
if(!setjmp(Buf))
longjmp(Buf2, 1);
}
}
int main (int argc, const char * argv[])
{
while(true)
{
if(!setjmp(Buf2))
{
MyFunction();
break;
}
longjmp(Buf, 1);
}
return 0;
}
What I except is that the code will jump back and forth from main to the function and back printing increasing number every time.
What actually happens is that it prints 0
and then 1
infinite number of times. it is as if when it jumps back into the function the stack is reset to defaults. why is it doing it? is there any way I can make it save the stack too?
I know setjmp
and longjmp
are even worse than goto
when it comes to coding style and readable code, but I am experimenting right now, and this code will probably never see the light of a usable application.