C++ longjmp() and setjmp()

The longjmp() function in C++ restores the environment previously saved by calling setjmp().

The longjmp() function is defined in <csetjmp> header file.

longjmp() prototype

void longjmp(jmp_buf env, int status);

The environment to load is stored in the argument env which is saved by calling setjmp() function.


longjmp() Parameters

  • env: An object of type jmp_buf that stores the environment to load.
  • status: The variable to return from setjmp. If it is equal to 0, 1 is used instead.

longjmp() Return value

  • None

Example: How longjmp() function works?

#include <iostream>
#include <csetjmp>
using namespace std;

int main()
{
	jmp_buf env;
	int val;
	
	val = setjmp(env);
	if (val==0)
	{
		cout << "setjmp returned " << val << endl;
		longjmp(env,val);
	}
	else
	{
		cout << "setjmp returned " << val << endl;
		cout << "Program terminating" << endl;
	}

	return 0;
}

When you run the program, the output will be:

setjmp returned 0
setjmp returned 1
Program terminating