exit() Function in main()

When exit() is used to exit from the program, destructors for locally scoped non-static objects are not called. The program is terminated without destroying the local objects.

Example of exit() in main()

C++




// C++ program to illustrate the
// working of exit() in main()
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
  
using namespace std;
  
class Test {
public:
    Test() { printf("Inside Test's Constructor\n"); }
  
    ~Test()
    {
        printf("Inside Test's Destructor");
        getchar();
    }
};
  
// Driver code
int main()
{
    Test t1;
  
    // using exit(0) to exit from main
    exit(0);
}


Output

Inside Test's Constructor

As we can see in the above example, the destructor of the local object is not called before the program’s termination.

One thing to note here is that the static objects will be cleaned up even when we call exit(). For example, see the following program:

Example of exit() in main() for Static Objects

C++




// C++ Program to illutrate the distruction of static
// objects while using exit()
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
  
using namespace std;
  
class Test {
public:
    Test() { printf("Inside Test's Constructor\n"); }
  
    ~Test()
    {
        printf("Inside Test's Destructor");
        getchar();
    }
};
  
// driver code
int main()
{
    static Test t1; // Note that t1 is static
  
    exit(0);
}


Output

Inside Test's Constructor
Inside Test's Destructor

Return Statement vs Exit() in main() in C++

The return statement in C++ is a keyword used to return the program control from the called function to the calling function. On the other hand, the exit() function in C is a standard library function of <stdlib.h> that is used to terminate the process explicitly.

The operation of the two may look different but in the case of the main() function, they do the same task of terminating the program with little difference. In this article, we will study the difference between the return statement and exit() function when used inside the main() function.

Similar Reads

exit() Function in main()

When exit() is used to exit from the program, destructors for locally scoped non-static objects are not called. The program is terminated without destroying the local objects....

return Statement in main()

...

Difference between return Statement and exit() Function

...

Contact Us