Ambiguity in definition of setjmp/longjmp makes them much less useful

Richard Tobin richard at aiai.ed.ac.uk
Wed Oct 10 03:50:36 AEST 1990


In article <1597 at redsox.bsw.com> campbell at redsox.bsw.com (Larry Campbell) writes:
>My real question is this:  Why not define the behavior of setjmp/longjmp so
>that the values of ALL local variables are defined, whether or not they've
>been allocated to registers?  Otherwise, setjmp/longjmp are significantly
>less useful.

The answer is that it's harder and slower.  Either you have to store all
the local variables in memory (which is why volatile works) or longjmp()
has to restore the registers to the right values by "unwinding" the stack,
and doing the restores as if each procedure were returning.  BSD on the
VAX uses the latter approach, but it would be harder for a compiler
that wanted to be cleverer about register allocation.

What usually happens is that setjmp() saves the values of the
registers, and longjmp() restores them.  This means that variables
which happened to be in registers get restored to the values they
had when setjmp() was called - that is, intermediate assignments are
lost.

It might be possible to be clever and just ensure all variables are in
memory before calling a procedure that might do a longjmp(), but the
compiler would have to be sure that longjmp() couldn't be called 
asynchronously from a signal handler.

Since ANSI only says that variables which have been changed are undefined,
it's hard to think of an implementation that would not result in either
the right value or the setjmp() value after a longjmp().

-- Richard
-- 
Richard Tobin,                       JANET: R.Tobin at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.lang.c mailing list