setjmp/longjmp

Rex Jaeschke rex at aussie.UUCP
Fri Apr 28 03:11:26 AEST 1989


Let me see if I can shed some light with an example. The following is 
taken verbatim from my latest book "Portability and the C Language" 
published by Hayden last October. Its, in the setjmp/longjmp chapter 
page 254.

==================================================================
#include <stdio.h>
#include <setjmp.h>

main()
{
	jmp_buf buffer;
	int i;
	int j = 10;
	register int k = 100;
	void test();

	i = setjmp(buffer);
	printf("setjmp return = %d\n", i);
	printf("j = %d, k = %d\n", j, k);

	j += 10;
	k += 20;
	if (i == 0)
		test(buffer);
}

void test(buffer)
jmp_buf buffer;
{
	longjmp(buffer, 1);
}

setjmp return = 0
j = 10, k = 100
setjmp return = 1
j = 20, k = 100

The first time through, j and k have the expected
values.  However, although both are incremented before test is
called, when longjmp returns control to setjmp, only j's
value is still intact.  The value of k was restored to its
initial value 100 rather than to 120.  For this implementation, it
appears the register variable is not preserved, while the auto
is, assuming, of course, the register variable actually is stored in a
register.  It could well be the opposite way around [[ or both or 
neither could be presevred.]]  In any case,
the result is undefined, and therefore unreliable, as we have
demonstrated.
==================================================================

Rex

----------------------------------------------------------------------------
Rex Jaeschke     | C Users Journal     |  Journal of C Language Translation
(703) 860-0091   | DEC PROFESSIONAL    |1810 Michael Faraday Drive, Suite 101
uunet!aussie!rex | Programmers Journal |     Reston, Virginia 22090, USA
----------------------------------------------------------------------------



More information about the Comp.std.c mailing list