Why does the main function work with no return value?

In C++, int main() can be left without a return value at which point it defaults to returning 0.

5.1.2.2.3 Program termination

1 If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

But you should be better of using EXIT_SUCCESS or EXIT_FAILURE for return from main().

Even though you're returning an int, some OSes (Windows) truncate the returned value to a single byte (0-255). Unix does the same, as do most other operating systems probably.Returning anything other than EXIT_SUCCESS or EXIT_FAILURE is asking for trouble

A Quote from GNU Library

Some non-POSIX systems use different conventions for exit status values. For greater portability, you can use the macros EXIT_SUCCESS and EXIT_FAILURE for the conventional status value for success and failure, respectively. They are declared in the file stdlib.h.

— Macro: int EXIT_SUCCESS This macro can be used with the exit function to indicate successful program completion.

On POSIX systems, the value of this macro is 0. On other systems, the value might be some other (possibly non-constant) integer expression.

— Macro: int EXIT_FAILURE This macro can be used with the exit function to indicate unsuccessful program completion in a general sense.

On POSIX systems, the value of this macro is 1. On other systems, the value might be some other (possibly non-constant) integer expression. Other nonzero status values also indicate failures. Certain programs use different nonzero status values to indicate particular kinds of "non-success". For example, diff uses status value 1 to mean that the files are different, and 2 or more to mean that there was difficulty in opening the files.


Normally it is not allowed for the control flow to reach the end of a non-void function without returning something. The main function is handled differently, as specified in the standard.

From http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2960.pdf:

§ 3.6.1/5

If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

As for the rationale, I'm not sure, honestly. If someone knows, please add it to my answer or as a comment.

Tags:

C++