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


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
";    }    ~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
";    }    ~Method() {       cout << "Destructor";    } }; int main() {    Method m;    exit(0); }

Output

Constructor

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements