My Herb Schildt book on C++ says: "... In C++, if a function is declared as returning a value, it must return a value." However, if I write a function with a non-void return type and do not return anything, the compiler issues a warning instead of an error: "Control reaches end of non-void function."
I use gcc (MinGW) and have set the -pedantic flag.
The analyzer has detected a non-void function with an execution path that does not return a value. Such a function results in undefined behavior. Flowing off the end of a non-void function with no 'return' results in undefined behavior.
In a main function, the return statement and expression are optional.
A void function will automatically return to the caller at the end of the function. No return statement is required.
Every function must have at least one return statement. A procedure is not required to have any return statements. The expression in a function's return statement must evaluate to a type that matches the return type in the function's declaration.
§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;
.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With