0

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 =)

Community
  • 1
  • 1
Logan Besecker
  • 2,733
  • 4
  • 23
  • 21

4 Answers4

1

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_SUCCESS on success, or EXIT_FAILURE on failure - the constants are defined in <cstdlib>.

If you like, you can omit the return statement from the end of main - the result will be the same as returning zero. This is a special case for main only - you must still return a value from any other non-void function.

Other than the OS and command line, is there anything else that can call a main function?

No - C++ specifically prohibits calling main from within the program.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

The return usually indicates whether the process executed correctly or not. For example, you could return a -1 if there was an error.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

The return value provides an exit status to the caller. When you return or exit(0) that indicates that your program ran and completed successfully. If you determine that your program has not completed successfully you can return other values. By the way the signature is int main.

Joe
  • 56,979
  • 9
  • 128
  • 135
0

It is the value returned to the OS. For example on UNIX based systems you can poll the value on your shell or in a script using $?

Sid
  • 7,511
  • 2
  • 28
  • 41