变量的值对函数的递归调用

时间:2016-07-23 03:47:37

标签: c++ c function parameter-passing

考虑功能

void solve(int arr[],int ind,int sum,int n,int count)
{
    if(ind==n){
          if(sum>max)
              max=sum;
      }
      else{
          sum+=arr[ind];//sum
          if(ind==n-1)
            solve(arr,ind+1,sum,n,1);//1st call
          if(ind==n-2 && count>1)
            solve(arr,ind+2,sum,n,1);//2nd call
          if(ind<n-1 && count<2){
              count++;
              solve(arr,ind+1,sum,n,count);//3rd call
          }
          if(ind<n-2)
              solve(arr,ind+2,sum,n,1);//4th call
          if(ind<n-3)
              solve(arr,ind+3,sum,n,1);//5th call
      }
}

我对逻辑没有任何问题,但对变量的传递感到困惑。我无法确定整数sum+=arr[ind] //sum是否在每次调用中作为相同的变量传递,或者是否在每次调用后都更新调用函数?

2 个答案:

答案 0 :(得分:2)

sum按值传递,因此不会更新该值。以下5个solve调用将以相同的sum值传递。

如果您希望在每次通话后更新sum,则应通过引用将其传递:void solve(int arr[],int ind,int &sum,int n,int count)

答案 1 :(得分:1)

每次调用函数sumlocally的值都会更新,但solve。您可以通过在函数定义中打印sum的值来显示它。

见下面的例子。

#include <stdio.h>
void call(int);
int main(void) {
    // your code goes here
    call(5);
    return 0;
}
void call(int sum)
{
    if(sum>15)
      return;
    printf("%d ",sum);
    sum+=5;
    call(sum);

}

o / p为5 10 15

这可能会帮助您更清晰地形象化。