Re: UB when flowing off end of value-returning function
Scott Meyers 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?
Beyond all pros and cons mentioned in the discussion the basic problem
is in my opinion the the language does not provide a way to declare a
function that must never return normally. The use cases would be
exception factories as well as some library functions like abort(). In
kernel programming it might be useful too. I missed that several times.
I have seen proprietary extensions for that purpose many years ago with
Watcom C++.
However, maybe the standard did not want to force the impact that every
compiler must do a full code path analysis.
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"; };
I guess, that this is simply a bug (from the compilers point of view).
The lambda implementations are quite new.
Marcel
Btw. The second feature I regularly miss is to declare a function as
side effect free, which implies that the return value is a compile time
constant if all arguments are compile time constant.
I have seen (and used) this on a very old compiler for the inmos
Transputer platform. Looking at the generated code this turned out to
give the compiler room for very advanced optimizations.
Of course, it makes no difference as long as the code is inlined. But
this is not always an option, e.g. because PIMPL.