Using the exit and atexit functions - C++ Function

C++ examples for Function:Useful Function

Description

Using the exit and atexit functions

Demo Code

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

void print(); /*from   www. ja v  a  2 s.c  om*/

int main() 
{ 
    atexit( print ); // register function print 

    cout << "Enter 1 to terminate program with function exit" 
          << "\nEnter 2 to terminate program normally\n"; 

    int answer; 
    cin >> answer; 

    // exit if answer is 1 
    if ( answer == 1 ) 
    { 
       cout << "\nTerminating program with function exit\n"; 
       exit( EXIT_SUCCESS ); 
    } 

    cout << "\nTerminating program by reaching the end of main" 
          << endl; 
} 

// display message before termination 
void print() 
{ 
    cout << "Executing function print at program termination\n" 
          << "Program terminated" << endl; 
}

Result


Related Tutorials