Possible Duplicate:
What should main() return in C/C++?
#include<stdio.h>
int main()
{
return 0;
}
In the code snippet given above, where does the return 0 returned by main go? Or in other words which function called the main function in the beginning.
main
is called by some startup function in the C runtime library. The C language standard says that returning frommain
is equivalent to calling theexit
function, so most C runtimes look something like this:The exit status gets passed back to the operating system, and then what happens from there is OS-dependent.
When you compile and link your program, the executable file format (e.g. PE or ELF) contains a start address, which is the virtual address at which execution begins. That function is typically part of the C runtime library (like the example
_start
above). That function has to end by calling a system call such asexit
, since if it just returned, it would have nowhere to go to: it would just pop an address off the stack and jump to that location, which would be garbage.Depending on how the OS loader initializes processes, the program arguments
argc
,argv
, and other data (such as the environment) might either come in as function parameters (either through registers or the stack), or they might require system calls (e.g.GetCommandLine
on Windows) to retrieve them. But dealing with all of that is the job of the C runtime, and unless you're explicitly going out of your way to avoid using the C runtime, you needn't worry about those details.Your compiler targets a certain platform, which includes operating-system specific mechanisms for starting processes. Part of that platform specific code contains the return value of
main
. When you link your program into an executable, there is an OS-specific piece of binary code that your linker adds which takes care of callingmain
and reporting the return value back to the operating system.The return value goes to the hosted environment. Typically, operating system calls
main
and gets exits status of the program.It is called by the C startup library, a stub function that is called (almost) directly by the kernel. For example, on Linux and OS X, it's a function named
_start
. It has the same signature asmain()
and the operating system itself uses its return value.