C++ atexit()

The atexit() function in C++ registers a function to be called on normal program termination.

The atexit() function in C++ registers a function to be called on normal program termination.

atexit() prototype

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

This function is defined in <cstdlib> header file.


atexit() Parameters

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

atexit() Return value

The atexit() function returns:

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

Example 1: How atexit() function works?

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

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

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

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

	cout << "Registration successful" << endl;
	return 0;
}

When you run the program, the output will be:

Registration successful
Program Exiting Successfully

More than one function can be registered to execute on termination.

If more than one atexit functions are registered, they are executed in the reverse order, i.e. the function registered atlast is executed at first. The same function can be registered more than once.

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


Example 2: Registering multiple function with atexit()

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

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

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

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

int main()
{
	int x1, x2, x3;

	/* Executed at last*/
	x1 = atexit(exit1);
	x2 = atexit(exit2);

	/* Executed at first */
	x3 = atexit(exit3);
	if ((x1 != 0) or (x2 != 0) or (x3 != 0))
	{
		cout << "Registration Failed";
		exit(1);
	}

	cout << "Registration successful" << endl;
	return 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: atexit() 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;
	/* Program will terminate here */
	cout << "Division by zero";
}

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

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

	return 0;
}

When you run the program, the output will be:

Registration successful
Generates Exception