atexit() function in C++

In this tutorial, we will learn about atexit() function in C++. This function is used to call a function that must be executed before the program terminates. Its working and usage have been explained below.

atexit() function in C++ explained

The function atexit() is defined in <cstdlib> header. The syntax for this function is as follows:

extern "C++" int atexit (void (*func)(void)) noexcept;

The atexit() function returns zero if the passed function has been successfully registered and a non-zero value if the registration of the passed function is unsuccessful.

Once a function is successfully registered with atexit(), it is called and executed just before the program terminates. Have a look at the below C++ program.

#include <iostream>
#include <cstdlib>

using namespace std;

void fun()
{
  cout << "fun is called at the end before the program terminates." << endl;
}

int main()
{
  int ret = atexit(fun);
  if(!ret)
    cout << "fun registered successfully" << endl;
  else
    {
       cout << "fun registeration failed" << endl;
       exit(1);
    }  
  
  cout << "Returning from main(terminating the program)\n";
  
  return 0;
}

The above program gives the output:

fun registered successfully
Returning from main(terminating the program)
fun is called at the end before the program terminates.

We can use atexit() function for calling more than one function. In such cases, the functions will be executed in form of a stack. That is the function that was passed last with atexit() function is executed first and the function passed first will be executed last. Have a look at the given code to understand the concept.

#include <iostream>
#include <cstdlib>

using namespace std;

void fun1()
{
  cout << "fun1" << endl;
}

void fun2()
{
  cout << "fun2" << endl;
}

void fun3()
{
  cout << "fun3" << endl;
}


int main()
{
  int ret1, ret2, ret3;
  
  ret1 = atexit(fun1);	
  ret2 = atexit(fun2);
  ret3 = atexit(fun3);
  
  if(ret1!=0 || ret2!=0 || ret3!=0)
    {
       cout << "functions registeration failed" << endl;
       exit(1);
    }
  else
    cout << "functions registered successfully" << endl;
  
  
  cout << "Returning from main(terminating the program)\n";
  
  return 0;
}

Output:

fun registered successfully
Returning from main(terminating the program)
fun3
fun2
fun1

Also read: C++ isinf() function | check if given argument infinite

Leave a Reply

Your email address will not be published. Required fields are marked *