The candidate function is not viable: expects an l-value for the third argument

Compute the nth power of P (both p and n are a positive integer) using the recursive function myPowerFunction (int p, int n, int & currentCallNumber). currentCallNumber is a reference parameter and stores the number of function calls made so far. myPowerFunction returns the nth power of p.

int myPowerFunction(int p, int n, int &z) { z++; if(n==1)return p; else if(n==0)return 1; else if(n%2==0)return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z); else return myPowerFunction(p,n/2,z)*myPowerFunction(p,n/2,z)*p; } int main() { cout << myPowerFunction(3,4,1); } 
+6
source share
4 answers

You need a variable to pass as the third argument to main_program. You cannot pass a constant as a non-constant reference.

 int count = 0; std::cout << myPowerFunction(3, 4, count) << 'n'; std::cout << count << '\n'; 
+10
source

The third parameter expects an lvalue, so you cannot pass a numeric constant there, so a possible solution might be:

 int z = 1; cout<< myPowerFunction(3,4,z); 

or better to create a function that calls recursive:

 int myPowerFunction(int p, int n) { int z = 1; return myPowerFunction(p,n,z); } 
+2
source

In myPowerFunction(3,4,1) literal 1 cannot be passed to a non- const reference, because this value is prvalue [basic.lval]. You need to store the value in a variable, and then use this variable when calling the function.

 int z = 0; std::cout << myPowerFunction(3, 4, z); 
+1
source

You do not need to specify a link as a parameter, as many here indicate. But yes, your input for z cannot be changed since it comes from read-only memory. Treat the input for z as const , internally copy z and pass the copy as a link. Then your desired use works:

 int myPowerFunction(int p, int n, const int &z) // z is now const ! { int _z = z + 1; // copy ! if (n == 1) return p; else if (n == 0) return 1; else if (n % 2 == 0) return myPowerFunction(p, n /2 , _z) * myPowerFunction(p, n / 2, _z); else return myPowerFunction(p, n / 2, _z) * myPowerFunction(p, n / 2, _z) * p; } int main() { std::cout << myPowerFunction(3, 4, 1); } 
0
source

Source: https://habr.com/ru/post/1243705/


All Articles