Point to watch: the only reliable way to ensure that a local variable retains the value that it had at the
time of the longjmp is to declare it volatile. (This is for variables whose value changes between the
execution of setjmp and the return of longjmp.)
A setjmp/longjmp is most useful for error recovery. As long as you haven't returned from the function
yet, if you discover a unrecoverable error, you can transfer control back to the main input loop and
start again from there. Some people use setjmp/longjmp to return from a chain of umpteen functions at
once. Others use them to shield potentially dangerous code, for example, when dereferencing a
suspicious pointer as shown in the following example.
switch(setjmp(jbuf)) {
case 0:
apple = *suspicious;
break;
case 1:
printf("suspicious is indeed a bad pointer\n");
break;
default:
die("unexpected value returned by setjmp");
}
This needs a handler for the segmentation violation signal, which will do the corresponding
longjmp(jbuf,1) as explained in the next chapter. Setjmp and longjmp have mutated into the
more general exception routines "catch" and "throw" in C++.
Programming Challenge
Jump to It!
Take the source of a program you have already written and add setjmp/longjmp to it,
so that on receiving some particular input it will start over again.
The header file <setjmp.h> needs to be included in any source file that uses setjmp or
longjmp.
Like goto's, setjmp/longjmp can make it hard to understand and debug a program. They are best
avoided except in the specific situations described.