In C++ Difference return statement vs exit(0) in main()
When we use exit(0) to exit our program, destructors for locally scoped non- static objects is not called while in return 0, destructors are called.
Note destructor has code to release resources.
static objects will be cleaned up if we call exit() or return 0.
eg:
class Test {
public:
Test() {
printf("Inside Test's Constructor\n");
}
~Test(){
printf("Inside Test's Destructor");
getchar();
}
};
int main() {
Test t1;
// using exit(0) to exit from main
exit(0);
}
Output:
Inside Test’s Constructor
While if we used return statement instead of exit(), output will be :
Output:
Inside Test’s Constructor
Inside Test’s Destructor
If we have static object
eg: static Test t2 ;// t12 is static
Then we get same output in both cases.
Output:
Inside Test’s Constructor
Inside Test’s Destructor