#include <iostream>
using namespace std;
string test(string s)
{
string rv = "Hey Hello";
if(s=="")
return rv;
else
cout<<"Not returning"<<endl;
}
int main()
{
string ss = test("test");
cout<<ss<<endl;
}
The above code should not return any value and probably print garbage, but its returning "Hey Hello" even without return statement at the end in test function. Can you tell my why its behaving like this?
reaching the end of a function returning non-void without any return statement is undefined behavior
you should have compiler warning for this kind of things if they are active
compiler are allowed to assume that undefined behavior is unreachable so the compiler have probably deleted the if statement and kept only the branch that doesn't lead to undefined behavior
Sincerely I'm surprised that this code is compiling! You should consider the warnings as errors. Warnings are important.
My guess is that the compiler writer thought:
whenever the coder has a branch without return statement it probably means that she knows that the branch cannot be visited (for instance a precondition on the arguments is checked before calling the function) so the branch can be removed.
This could explain why the compiler behaves in this way. But a more formal answer to your question is: "this is undefined behavior, everything could happen".
When trying to compile it with gcc the output depends on the optimization level.
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