C++ exit() Standard Library Function

- March 13, 2018
The exit() function is used to terminate program execution. Normally, terminates process, performing the regular cleanup for terminating programs. After program termination, the control shifts to the operating system environment and performs the following operations at the same time:
  • All open functions with cstdio header file (c streams) are closed (and flushed, if buffered).
  • Objects associated with the current thread with thread storage duration are closed.
  • Objects with static storage duration are destroyed (C++) and functions registered with atexit are called.
  • All files created with tmpfile are removed.

Declaration

The exit() function located in stdlib header file. The general syntax to call this function is as follows:

exit (num);
Where:
num It indicates the integer value. For example if 0 is used then its mean that the program termination is normal.

Example Program


// exit function example

#include <iostream.h>

#include <stdlib.h>

using namespace std;

int main()

{

    cout<<"Program will exit"<<endl;

    exit(1); // Returns 1 to the operating system

    cout<<"Never executed";

}

We can use the constants EXIT_SUCCESS and EXIT_FAILURE, defined in STDLIB.H, to indicate success or failure of the program.