I have a few questions relating to setjmp/longjmp usage –
-
What is the use of setjmp(jmp___buf stackVariables) returning 0. It is a default, which we cannot influence.
-
Is the only significance of setjmp(stackVariables) is to push the stack in stackVariables. And basically 0 tells us if the stack was pushed on stack_variables successfully.
-
Their is one occasion when the value is non-zero (any non-zero) when you return from a longjmp. What is returning from a lomgjmp, when do you return from longjmp, when your exception is handled. This is setup is really confusing.
-
Can some please relate it to try/throw and catch. And would be really great, if some good examples of setjmp/longjmp could be provided.
-
Is longJmp like throw, and it is called just after the place where exception can be raised.
Thanks.
The C99 spec gives:
So the answer to 1 is that a zero indicates you have called
setjmpthe first time, and non-zero indicates it is returning from alongjmp.It pushes the current program state. After a longjmp, the state is restored, control returns to the point it was called, and the return value is non-zero.
There are no exceptions in C. It’s sort-of similar to
forkreturning different values depending whether you’re in the original process, or a second process which has inherited the environment, if you’re familiar with that.try/catchin C++ will call destructors on all automatic objects between the throw and the catch.setjmp/longjmpwill not call destructors, as they don’t exist in C. So you are on your own as far as callingfreeon anything you’vemalloced in the mean time.With that proviso, this:
is roughly equivalent to
In the C case, you have to do explicit memory management (though normally you’d free it in the function which malloc’d it before calling longjmp as it makes life simpler)