6

When writing a C/C++ program, specifically with latest compilers, why do we need to return an integer from the main() method? Like int main() and we return "return 0" from it. So what is the exact reason behind this?

elixenide
  • 44,308
  • 16
  • 74
  • 100
TheSpy
  • 265
  • 1
  • 8
  • 21
  • 3
    so as to indicate that the function exited _normally_. – devnull Feb 01 '14 at 06:29
  • See http://stackoverflow.com/questions/204476/what-should-main-return-in-c-and-c – Brian Bi Feb 01 '14 at 06:30
  • return value is called `'Program termination status'` (that should be read by parent process), Instead of returning `0` or `1` You should `return EXIT_SUCCESS` or `EXIT_FAILURE` and call exit with these value as `exit(EXIT_FAILURE);`. Say if child process termination status was failure then parent process may need to do some cleanup works – Grijesh Chauhan Feb 01 '14 at 06:59
  • Remember at Stack-overflow you can accept **only one** answer! Yes you can vote all answers. – Grijesh Chauhan Feb 01 '14 at 09:31

5 Answers5

14

The return value of main() becomes the exit status of the process. Traditionally, an exit status of zero usually means “OK,” while any non-zero value indicates some kind of error. This is analogous with how many system calls likewise return zero or an error code.

Even more information at J. Leffler's epic answer to this, similar question: What should main() return in C and C++?

Community
  • 1
  • 1
BRPocock
  • 13,638
  • 3
  • 31
  • 50
8

As you say, main() is declared as int main(). The OS expects an integer back, so it knows what to do next, especially if another program or script invoked your program. 0 means "no error." Anything else means an error occurred.

elixenide
  • 44,308
  • 16
  • 74
  • 100
4

The int value returned by main(), if any, is the program's return value to 'the system'. A zero value from main() indicates success. A nonzero value indicates failure. If no value is returned, the system will receive a value indicating successful completion.

neverhoodboy
  • 1,040
  • 7
  • 13
4

It returns the 0 to OS to tell the OS that your program executed successfully.

  • 4
    no, the OS won't care what the program returns, it just stores this and provides to other programs that have executed this program or scripts who may read this to use on their own, if needed – phuclv Feb 02 '14 at 06:59
2

See Why default return value of main is 0 and not EXIT_SUCCESS?.

Returning zero from main() does essentially the same as what you're asking. Returning zero from main() does not have to return zero to the host environment.

From the C90/C99/C++98 standard document:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

In other words, the specific value indicates success.

Community
  • 1
  • 1