Possible Duplicate:
What should main() return in C/C++?
What does main return?
I’ve been wondering this for a while: what is the purpose of a return 0; statement at the end of the main() function?
I know that a return statement at the end most functions returns a value to the function which called it. However, as I understand it, the main function is the starting and ending point of the program, so I’m a little confused as to why it has a return type at all?
main()
{
//code goes here
return 0; // <-- what is the point of this return statement?
}
edit: I’m pretty new to programming (first year computer science student) and after looking at some of the answers it sounds like the return statement is used to tell the caller of the function if it has completed successfully. Other than the OS and command line, is there anything else that can call a main function? thanks for the quick answers =)
It’s used to tell the environment running the program whether or not it completed successfully. This is important for command-line tools if you want to run them from scripts.
You should return zero or
EXIT_SUCCESSon success, orEXIT_FAILUREon failure – the constants are defined in<cstdlib>.If you like, you can omit the
returnstatement from the end ofmain– the result will be the same as returning zero. This is a special case formainonly – you must still return a value from any other non-void function.No – C++ specifically prohibits calling
mainfrom within the program.