Exception Handling - Example 2 - longjmp()

#include <iostream>
#include <setjmp.h>
using namespace std;

class X
{
public:
	X() { cout << "X constructor\n"; }
	~X() { cout << "X destructor\n"; }
};

void funk(jmp_buf);

int main(void)
{

	int value;
	jmp_buf jumper;	// declare a jump buffer to save program state

	value = setjmp(jumper);	// store the program state
	if (value != 0)
		cout << "longjmp() called with value " << value << endl;
	funk(jumper);		// call some function
	cout << "End of program\n";

	return 0;
}

void funk(jmp_buf jumper)
{
	X x;
	cout << "Do you want to test longjmp() ? ";
	char c;
	cin >> c;
	if (c == 'y') longjmp(jumper,1);
}


Program Execution

First run:

X constructor
Do you want to test longjmp() ? n
X destructor
End of program

Second run (GNU compiler)

X constructor
Do you want to test longjmp() ? y
longjmp() called with value 1
X constructor
Do you want to test longjmp() ? n
X destructor
End of program

Second run (MS Visual C++ 2008 & Borland 5.5 Compilers)

X constructor
Do you want to test longjmp() ? y
X destructor
longjmp() called with value 1
X constructor
Do you want to test longjmp() ? n
X destructor
End of program