I understand that setjmp saves the content of the registers (sp,fp,pc) so that longjmp can restore them later. And when longjmp is called, it makes (kind of) setjmp return the passed ret val. However, in the below program, I am little confused with the flow.
1 #include <setjmp.h>
2 #include <stdio.h>
3
4 jmp_buf env;
5
6 void hello()
7 {
8 int ret = setjmp(env);
9 if(ret != 0)
10 {
11 printf("error\n");
12 }
13 printf("hello called\n");
14 }
15
16 int main() {
17 printf("hello main\n");
18 hello();
19 printf("after hello call\n");
20 longjmp(env,1);
21 printf("after long jump\n");
22 return 0;
23 }
Output (I was not expecting this)
---------------------------------
hello main
hello called
after hello call
error
hello called
I was expecting an endless loop here, because when longjmp gets called, the ret in hello should be 1 (which is as per output) but then, once hello() has returned at this point, I should have again fallen at line 19 and hence again calling longjmp at line 20. Please help me understand the behaviour here.