这是我的代码。我希望它返回 5,因为增量为 1。问题是如果 x >= 5,那么如何将值返回给主函数?函数中应该只有 1 个返回。
int addup(int x)
{
if (x < 5)
{
std::cout<< x++;
addup(x);
}
else return x;
}
int main()
{
using namespace std;
int x = 0;
cout << "And x is:" << addup(x) << endl;
cin.clear();
cin.ignore(32767, '\n');
cin.get();
return 0;
}
最佳答案
递归调用中缺少返回
。
替换
addup(x);
通过
return addup(x);
如果该行中没有 return
,该函数只会在最后消失,并且会出现未定义的行为。
好的编译器会警告您 if
block 中缺少 return
语句。当使用 -Wall
编译时,我从 g++ 收到以下警告:
socc.cc: In function ‘int addup(int)’:
socc.cc:11:1: warning: control reaches end of non-void function [-Wreturn-type]
}
关于C++ 递归不返回期望值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37096345/