return statement vs exit() in main() C++

CProgrammingServer Side Programming

return statement

The return statement terminates the execution of function and it returns the control to the calling function. It calls the constructor as well as the destructor. It returns an integer value for “int main()”.

The following is the syntax of return statement.

return expression;

Here,

expression − The expression or any value to be returned.

The following is an example of return statement.

Example

 Live Demo

#include<iostream>
using namespace std;
class Method {
   public:
   Method() {
      cout << "Constructor\n";
   }
   ~Method() {
      cout << "Destructor";
   }
};
int main() {
   Method m;
   return(0);
}

Output

Constructor
Destructor

exit()

The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function is called, the process gets terminated. It calls the constructor of class only. It is declared in “stdlib.h” header file in C language. It does not return anything.

The following is the syntax of exit()

void exit(int status_value);

Here,

status_value − The value which is returned to parent process.

The following is an example of exit().

Example

 Live Demo

#include<iostream>
using namespace std;
class Method {
   public:
   Method() {
      cout << "Constructor\n";
   }
   ~Method() {
      cout << "Destructor";
   }
};
int main() {
   Method m;
   exit(0);
}

Output

Constructor
raja
Published on 06-Nov-2018 11:05:57
Advertisements