Search code examples
c++c++11iso

Returning a value on function exit in C++


Is it true that in C++ main () is not required to include a return 0;?

Does it apply to main only or to any non-void function?

Is it new in C++11 or was it always like that?

What is the rationale?


Solution

  • The main() function is guaranteed to return 0 if you do not return explicitly a value. This is defined in the ISO standard:

    3.6.1/5: A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

    return 0;

    This special behavior is only for main(), because main() is a function returning an int, and the standard defines the general rule:

    6.6.3/2 Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

    Now, was it always like that ? Bjarne Stroutsturp in the C++ Programming language, in its edition of 1986, long before any standardization, suggests this. In most of his examples of his tutorial chapter, main() doesn't return a value, and on page 82 of this early edition, he states:

    Conventionally, main() returns 0 if the program terminates normally and non zero otherwise, so returning the number of errors accomplishes this nicely

    Additional remarks

    In this book, the rule is however implicit from the examples and acompanying explanations; Stroustrup didn't state explicitly a general unambiguous rule for main() nor didn't he mention it in his The Design and evolution of C++ book of 1994.

    To be noted that in C89 the principle was still undefined behavior in absence of explicit return value, until arrival of C99. But in C++98 the current 0 return by default rule was already formalized. So I think it's not for backward compatibility with C.