m.rossi m.rossi - 7 months ago 26
C++ Question

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
only or to any non-void function?

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

What is the rationale?


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 otherwhise, so returning the number of errors accomplishes this nicely