奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息

Strange (for me) return statement - can't find any information on google about it

本文关键字:谷歌 找不到 于它 信息 任何关 声明 对我来说 返回      更新时间:2023-10-16

我使用递归制作了一个C++程序,该程序返回数字中的最大数字
我按自己的方式工作,但我找到了另一种选择:

int cifmax(int n) {
if(n <= 9)
return n;
return max(n % 10, cifmax(n / 10));
}

第二次返程是怎么回事?

您可以将此代码视为等效于以下更详细的版本:

int cifmax(int n) {
if (n <= 9){
return n; // trivial base case
} else {
int currentdigit = n % 10; // the least significant digit
int otherdigits = n / 10; // other digits past the least significant
int maxofotherdigits = cifmax(otherdigits); // make the recursive call
// compute maximum of the two
if (currentdigit > maxofotherdigits){
return currentdigit;
} else {
return maxofotherdigits;
}
}
}

注意以下片段:

if (currentdigit > maxofotherdigits){
return currentdigit;
} else {
return maxofotherdigits;
}

相当于:

return std::max(currentdigit, maxofotherdigits);

其中std::max返回其两个参数中较大的一个。