28.5 setjmp and longjmp

I l @ ve RuBoard

C has its own way of handling exceptions through the use of setjmp and longjmp . The setjmp function marks a place in a program. The longjmp function jumps to the place marked by setjmp .

Normally setjmp returns a zero. This tells the program to execute normal code. When an exception occurs, the longjmp call returns to the location of the setjmp function. The only difference the program can see between a real setjmp call and a fake setjmp call caused by a longjmp is that normally setjmp returns a zero. When setjmp is "called" by longjmp , the return value is controlled by a parameter to longjmp.

The definition of the setjmp function is:

 #include <setjmp.h> int setjmp(jmp_buf env); 

where env is the place where setjmp saves the current environment for later use by longjmp .

The setjmp function return values are as follows :

Normal call

Nonzero

Non-zero return codes are the result of a longjmp call.

The definition of the longjmp call is:

 void longjmp(jmp_buf env, int return_code); 

where env is the environment initialized by a previous setjmp call, and return_code is the return code that will be returned by the setjmp call.

Figure 28-1 illustrates the control flow when using setjmp and longjmp .

Figure 28-1. setjmp/longjmp control flow
figs/c++2_2801.gif

There is one problem here, however. The longjmp call returns control to the corresponding setjmp . It does not call the destructors of any classes that are " destroyed " in the process .

In Figure 28-1 we can see that in the subroutine we define a class named a_list . Normally we would call the destructor for a_list at the end of the function or at a return statement. However, in this case we use longjmp to exit the function. Since longjmp is a C function, it knows nothing about classes and destructors and does not call the destructor for a_list . So we now have a situation where a variable has disappeared but the destructor has not been called. The technical name for this situation is a "foul-up."

When converting C to C++, change all setjmp / longjmp combinations into exceptions.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net