我最近读到递归使用系统堆栈来存储函数调用的返回地址。所以,我只是做了一个随机代码来理解递归中的这个 LIFO 概念
int fun( int x)
{ if ( x<6 || x>6 )
{ cout<<x;
return 0;
}
else
return max(fun(x-1),fun(x+1));
}
int main(){
cout<<fun(6);
return 0;
}
我期望输出
570
实际输出为
750
我假设函数将按此顺序调用-
fun(6)->fun(5) { it will print 5 then return 0} ->fun(7) { it print 7 then return 0} -> max(0,0) { return 0}
纠正我,我哪里错了。