In C++, what happens when a function that is supposed to return an object ends without a return statement? What gets returned?
e.g.
std::string func() {}
What gets returned?
We don't know. According to the standard, the behavior is undefined.
§6.6.3/2 The return statement [stmt.return]:
(emphasis mine)
Flowing off the end of a constructor, a destructor, or a function with a cv
void
return type is equivalent to areturn
with no operand. Otherwise, flowing off the end of a function other thanmain
(basic.start.main) results in undefined behavior.
In fact most compilers would give a warning for it, like Clang:
warning: control reaches end of non-void function [-Wreturn-type]
In C++, what happens when a function that is supposed to return an object ends without a return statement?
It causes undefined behavior. No one can tell what exactly will happen.
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