return Statement in main()
When the return statement is used inside the main() function, the program control is transferred to the calling function, which in this case is the Operating System. So, using a return statement in main() terminates the program execution which is similar to the operation of the exit() function.
Example of return in main()
C++
// C++ Program to illustrate the working // of return in main() #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; class Test { public : Test() { printf ( "Inside Test's Constructor\n" ); } ~Test() { printf ( "Inside Test's Destructor\n" ); } }; // driver code int main() { Test t1; static Test t2; // using return 0 to exit from main return 0; } |
Inside Test's Constructor Inside Test's Constructor Inside Test's Destructor Inside Test's Destructor
As we can see, all the objects’ (local or static) destructor is called before exiting the program which was not the case with the exit() function.
Return Statement vs Exit() in main() in C++
The return statement in C++ is a keyword used to return the program control from the called function to the calling function. On the other hand, the exit() function in C is a standard library function of <stdlib.h> that is used to terminate the process explicitly.
The operation of the two may look different but in the case of the main() function, they do the same task of terminating the program with little difference. In this article, we will study the difference between the return statement and exit() function when used inside the main() function.