C++ at_quick_exit()

The at_quick_exit() function in C++ registers a function to be called on quick program termination i.e. terminated via quick_exit().

The function registered with at_quick_exit() function is called when quick_exit() function is called.

at_quick_exit() prototype

extern int at_quick_exit (void (*func)(void));

This function is defined in <cstdlib> header file.


at_quick_exit() Parameters

  • func: Pointer to the function to be called on quick program termination.

at_quick_exit() Return value

The at_quick_exit() function returns:

  • Zero if the function registration is successful.
  • Non zero if the function registration failed.

Example 1: How at_quick_exit() function works?

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

void bye()
{
	cout << "Program Exiting via quick_exit()";
}

int main()
{
	at_quick_exit(bye);
	cout << "Inside Main" << endl;

	quick_exit(0);
	return 0;
}

When you run the program, the output will be:

Inside Main
Program Exiting via quick_exit()

More than one function can be registered to execute on quick exit.

If more than one functions are registered using at_quick_exit(), they are executed in the reverse order, i.e. the function registered at last is executed at first. The same function can be registered more than once.

The number of functions calls that can be registered with at_quick_exit() depends on the particular library implementation. However the minimum limit is 32.


Example 2: Registering multiple function with at_quick_exit()

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

void quick_exit1()
{
	cout << "Exit Function 1" << endl;
}

void quick_exit2()
{
	cout << "Exit Function 2" << endl;
}

void quick_exit3()
{
	cout << "Exit Function 3" << endl;
}

int main()
{
	int x1, x2, x3;
	/* Executed at last*/
	x1 = at_quick_exit(quick_exit1);
	x2 = at_quick_exit(quick_exit2);

	/* Executed at first */
	x3 = at_quick_exit(quick_exit3);

	if ((x1 != 0) or (x2 != 0) or (x3 != 0))
	{
		cout << "Registration Failed";
		exit(1);
	}
	cout << "Registration successful" << endl;
	
	quick_exit(0);
}

When you run the program, the output will be:

Registration successful
Exit Function 3
Exit Function 2
Exit Function 1

If a registered function throws an unhandled exception when called on termination, the terminate() function is called.


Example 3: at_quick_exit() with function throwing unhandled exception

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

void bye()
{
	cout << "Generates Exception";
	int a = 5, b = 0;
	int x = a/b;
}

int main()
{
	int x;
	x = at_quick_exit(bye);

	if (x != 0)
	{
		cout << "Registration Failed";
		exit(1);
	}
	cout << "Registration successful" << endl;

	quick_exit(0);
}

When you run the program, the output will be:

Registration successful
Generates Exception
[The program will terminate with error]