The setjmp/longjmp (hereafter slj) feature in C is ugly, and its behavior may vary between implementations. Nonetheless, given the absence of exceptions, slj is sometimes necessary in C (note that C++ provides exceptions which are in almost every way superior to slj, and that slj interacts badly with many C++ features).
In using slj, one should bear in mind the following, assuming routine Parent() calls routine Setter(), which calls setjmp() and then calls Jumper, which in turn calls longjmp().
- Code may legally exit the scope in which a setjmp is performed without a longjmp having been executed; as soon as the scope exits, however, the previously-created jmp_buf must be regarded as invalid. The compiler probably won't do anything to mark it as such, but any attempt to use it may result in unpredictable behavior, likely including a jump to an arbitrary address.
- Any local variables in Jumper() will evaporate with the call to longjmp(), rendering their values irrelevant.
- Whenever control returns to Parent, via whatever means, Parent's local variables will be as they were when it called Setter, unless such variables had their addresses taken and were changed using such pointers; in any case, setjmp/longjmp will not affect their values in any way. If such variables do not have their addresses taken, it is possible that setjmp() may cache the values of such variables and longjmp() may restore them. In that scenario, however, there would be no way for the variables to change between when they are cached and when they are restored, so the cache/restore would have no visible effect.
- The variables in Setter may or may not be cached by setjmp() call. After a longjmp() call, such variables may have the value they had when setjmp() was performed, or the values they had when it called the routine which ultimately called longjmp(), or any combination thereof. In at least some C dialects, such variables may be declared "volatile" to prevent them from being cached.
Although setjmp/longjmp() can sometimes be useful, they can also be very dangerous. There is in most cases no protection errant code causing Undefined Behavior, and in many real-world scenarios, improper usage is likely to cause bad things to happen (unlike some kinds of Undefined Behavior, where the actual outcome may often line up with what the programmer intended).
setjmp()must still be in scope when you calllongjmp(). - bk1e