return vs exit() in main() in C++ with examples

In this tutorial, we will see the difference between using exit() and return inside the main() function. In C++ return is a keyword that returns the flow of execution to the calling function. Whereas exit() is a function that terminates the program at any point of usage.

Using return Keyword in main()

The return keyword terminates the current function and returns the control to the calling function. The return keyword is used in case of the return type functions such as int, char, float, etc. Using the return statement in the main() function successfully terminates the program as there is no need for transferring control.
Let us see an example program using the return keyword,

#include <iostream>
using namespace std;

class Return {
public:
  //Constructor
  Return() 
  {
    cout<<"Return Constructor Activated\n";
  }
   
   //Destructor
  ~Return()
  {
    cout<<"Return Destructor Activated";
  }
};

int main() 
{
  //Object of Return class  
  Return obj;
  
  //Using return in main 
  return 0;
}

Output

Return Constructor Activated
Return Destructor Activated

From the above program, we can conclude that using the return statement calls both the constructor and destructor of a class object irrespective of the scope of the object. Calling the destructor function is necessary to release dynamically allocated memory.

Using exit() Function in main()

The stdlib.h header file in C++ defines the exit() function. It instantly terminates the entire program instead of transferring control like the return keyword. The most significant difference between them is while working with objects of a class. Unlike the return statement the exit() function does not call the destructor if the object is non-static.
Let us see an example program using the exit() function,

#include <iostream>
#include<stdlib.h>
using namespace std;

//Exit class 1
class Exit {
public:
  //Constructor
  Exit() 
  {
    cout<<"Exit Constructor Activated\n";
  }
   
   //Destructor
  ~Exit()
  {
    cout<<"Exit Destructor Activated";
  }
};

//Exit class 2
class StaticExit {
public:
  //Constructor
  StaticExit() 
  {
    cout<<"Static Exit Constructor Activated\n";
  }
   
   //Destructor
  ~StaticExit()
  {
    cout<<"Static Exit Destructor Activated";
  }
};

int main() 
{
  //Non-static object  
  Exit obj;
  //Static object 
  static StaticExit obj1; 
  //Using exit() in main 
  exit(0);    
    
}

Output

Exit Constructor Activated
Static Exit Constructor Activated
Static Exit Destructor Activated

Apart from the non-static object, we have also declared a static object to illustrate the difference. We can clearly see that using exit() function does not call the destructor unless the object is scoped as static. The static storage area stores the static objects which need to be cleared during program termination.

You can also learn,

Leave a Reply

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