“return 0” vs “exit(0)” in main()

Difference between exit(0) and return 0 in C++:-When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.Program 1 – – uses exit(0) to exitclass Test {
public:
Test() {
cout<<“Inside Test’s Constructorn”;
}

~Test(){
cout<<“Inside Test’s Destructor”;
}
};

int main() {
Test t1;
exit(0); //using exit(0) to exit from main
}Output:-Inside Test’s ConstructorProgram 2 – uses return 0 to exitclass Test {
public:
Test() {
cout<<“Inside Test’s Constructorn”;
}

~Test(){
cout<<“Inside Test’s Destructor”;
}
};

int main() {
Test t1;
return 0; //using return 0 to exit from main
}Output:Inside Test’s Constructor
Inside Test’s DestructorCalling destructors is sometimes important, for example, if destructor has code to release resources like closing files,deleting dynamically allocated memory etc.if class object is static:-Note that static objects will be cleaned up even if we call exit().
Reason:-static objects are allocated storage in static storage area.static object is destroyed at the termination of program.For example, see following program.class Test {
public:
Test() {
cout<<“Inside Test’s Constructorn”;
}

~Test(){
cout<<“Inside Test’s Destructor”;
}
};

int main() {
static Test t1; ///* Note that t1 is static*/

exit(0);
}Output:Inside Test’s Constructor
Inside Test’s Destructor

News Reporter

Leave a Reply

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