Re: UB when flowing off end of value-returning function
On Nov 2, 5:09 pm, Scott Meyers <NeverR...@aristeia.com> wrote:
Both C++98/03 and draft C++0x say this:
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.
Does anybody know why this is undefined behavior instead of
a hard error?
Probably mainly historical reasons. Way, way back, before void,
functions implicitly returned int, if you didn't specify
anything else; functions which were logically void still
implicitly returned int, and often flowed off the end. By
declaring this undefined behavior, instead of a hard error, the
C folks allowed implementations to continue supporting such
code. And C++ follows suite for reasons of C compatibility.
It has an interesting implication for lambda expressions.
Lambdas declaring a return type but returning nothing yield UB
and, with the compilers I tested, don't necessarily issue
a warning:
auto f = []()->int { std::cout << "Oops, I forgot to return something"; };
All enlightenment appreciated.
There was never any question of requiring an error from the
compiler. It's almost impossible to determine reliably. It
wouldn't be very difficult (nor add much overhead) to require
some sort of runtime error, say abort after an implementation
defined message. For practical purposes, you can't do it for
int; some code that was written before void might still be in
use, fixed up just enough for it to pass the compiler. But it
would seem a reasonable requirement for other types.
--
James Kanze