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.
mainis called by some startup function in the C runtime library. The C language standard says that returning frommainis equivalent to calling theexitfunction, 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
_startabove). 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.GetCommandLineon 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.