递归如何使用堆栈数据结构



我最近读到,递归使用系统堆栈来存储函数调用的返回地址。因此,我只是制作了一个随机代码,以了解递归中的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}

纠正我,我在哪里弄错了。

在C 中,未指定参数的评估顺序。

编写max(fun(x-1),fun(x+1));时,编译器可以免费选择评估fun(x+1)

最新更新