Is a return statement mandatory for C++ functions that do not return void?
Solution 1:
§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.
So it depends on your definition of mandatory. Do you have to? No. But if you want your program to have well-defined behavior, yes.*
*main
is an exception, see §3.6.1/5. If control reaches the end of main
without a return
, it will have the effect of return 0;
.
Solution 2:
It is mandatory--it is an undefined behavior when such function ends without returning anything (so compilers might actually implement some kind of special behaviour). However, there are some special cases.
::main
is an exception, it is assumed that return 0;
is at the end of its code.
Also, you don't have to return a value in a function that does not return cleanly, f.e.:
int Foo() {
throw 42;
}