I think the main confusion here is the notion that that main
is the first and last thing that happens in C++ program. Whilst it is [1] the first part of YOUR program, there is usually some code in the application that sets up a few things, parses command line arguments, opening/initialization of standard I/O (cin
, cout
, etc) and other such things, which happen BEFORE main
is called. And main
is essentially just another function, called by the C++ runtime functionality that does that "fix things up before main
".
So, when main
returns, it goes back to the code that called it, which then cleans up the things that need cleaning up (closing standard I/O channels, and many other such things), before actually finishing up by calling some OS function to "terminate this process". As part of this "terminate this process" functionality is (in most OS's) a way to signal "success or failure" to the OS, so that some other process monitoring the application can determine "if all is well or not". This is where, eventually, the 0
(or 1
if you use return 1;
in main
) ends up.
[1] If there are static objects with constructors that are part of the user's code, then these will be performed before any code in main
[or at least, before any code in main
that belongs to the user's application] is executed.