0

The following code:

void fin(int Arr[],int& N,int& k,int& i,int& sum,int& count){
    if(i==N){
        if(sum==k){
            count++;
        }
        return;
    }
    sum+=Arr[i];
    fin(Arr,N,k,i+1,sum,count);
    sum-=Arr[i];
    fin(Arr,N,k,i+1,sum,count);
}

int findSubArraySum(int Arr[], int N, int k)
{
    // code here
    int count=0;
    int i=0;
    int sum=0;
    fin(Arr,N,k,i,sum,count);
    return count;
}

Gives the following compilation error:

prog.cpp: In member function void Solution::fin(int*, int&, int&, int&, int&, int&): prog.cpp:18:22: error: invalid initialization of non-const reference of type int& from an rvalue of type int fin(Arr,N,k,i+1,sum,count);

Can anybody help to solve it ?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • [What exactly is an R-Value in C++?](https://stackoverflow.com/a/9406672) – 001 Aug 12 '22 at 16:44
  • You cannot pass expressions like `i+1` which is an R-value as a non-const `int&` (an L-value ref). In your case since you don't change `N`,`k` and `i`, you can actually pass them as `int const &`. – wohlstad Aug 12 '22 at 16:46
  • So how do i pass the value of i and count to be able to change in the above recusrion code? – tushar sharma Aug 12 '22 at 17:02
  • One option is to increment `i`. For example: `fin(Arr, N, k , ++i, sum, count); sum -= Arr[i - 1]; fin(Arr, N, k, i, sum, count);` Or just don't make it a reference. There doesn't appear to be a need for a reference there. – 001 Aug 12 '22 at 17:10
  • how do I pass a variable from one function to another function and by passing it the value of that variable changes.In the above code i tried to pass count to fin function to update the count and then if after the whole code run i print the count variable value it should returned me the updated value. – tushar sharma Aug 12 '22 at 17:24

0 Answers0