setjmp and longjmp
In short, functions setjmp and longjmp just work like label&goto instruction, except that the combination of label&goto only can be used within the same function which means you cannot goto the label outside the function. But the combination of setjmp and longjmp can be used anywhere in the whole program.
For example, we use label&goto to implement a jump function:
main()
{
int a=1, b=2, c=0;
label:
c=a+b;
goto label;
}
Now we implement the same function using setjmp and longjmp:
typedef long jmp_buf[16];
main()
{
int a=1, b=2, c=0;
jmp_buff environment;
setjmp (evironment);
c=a+b;
longjmp(evironment, 1);
}
So from above, we can see the jump buffer environment contains all the context around the setjmp function, so it works like label. And then the longjmp function will jump to the position where environment assigned.
The prototype of setjmp and longjmp:
int setjmp(jmp_buff env);
void longjmp(jmp_buff env, int val);
So function longjmp never return any value, because it will just jump the execution flow to setjmp position, but once jump to setjmp position, the setjmp function will return the value assigned by val which is the second parameter of longjmp function.
The first time setjmp function is called, it will always return 0. But after longjmp is executed, and jump to setjmp function, setjmp will never return 0. (Even if you set val to 0, setjmp will also return 1).
To make every thing more clearer, let's see an example from reference [1]:
- #include<stdio.h>
- #include<setjmp.h>
- jmp_buf ebuf;
- int f2();
- int main()
- {
- int i;
- printf("1");
- i=setjmp(ebuf);
- if(i==0)
- {
- f2();
- printf("This will not beprinted.");
- }
- printf("%d",i);
- return 0;
- }
- int f2()
- {
- printf("2");
- longjmp(ebuf,3);
- }
The output of this example will print "1 2 3"
Reference:
[1] http://blog.csdn.net/sunlylorn/article/details/7178575
Comments
Post a Comment