#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;
}
上面的代码不应该返回任何值,可能会打印垃圾信息,但即使在test函数末尾没有return语句,它仍然返回“Hey Hello”。 你能告诉我为什么会这样吗?
test
函数中的else
分支是非法的,因此if
条件必须始终为真,从而优化函数以始终返回rv
。 - BoBTFish