ellen
ellen

Reputation: 704

"invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’": Recursive pass-by-reference function

I have a recursive function in a C++ class like this:

Class myClass{
    private:
       static const int MAX_ALPHA = 1000;
       static const int MAX_BETA = -1000;
    public:
       void startSearch();
       int  search(int& alpha, int& beta, int h);
       int  value();
   };

The implementation looks something like this:

void Class::startSearch(){
   int alpha = MAX_ALPHA;
   int beta = MAX_BETA;
   int h = 10;
   int score = search(alpha, beta, h);
}

int search(int& alpha, int& beta, int h){
   if(h == 0){
      return value(); 
   }
   //do some stuff
   int score = search(-beta, -alpha, h-1); // ERROR HERE
   //do some more stuff
   return score;
}

I"m confused about why the compiler gives me an error when I'm calling the search() function. It says: "error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’". The issue goes away when I don't pass by reference - however, I want to pass by reference.

Any help is appreciated and I am also happy to provide more info about the problem if needed. Thank you!

Upvotes: 3

Views: 3087

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

Note that the result returned by operator- are rvalues; so -beta and -alpha are both rvalues and then can't be bound to lvalue-reference to int, i.e. int&.

You can pass lvalues instead; if you don't want to change the parameter type of the function (and the arguments are supposed to be modified for pass-by-reference). e.g.

int search(int& alpha, int& beta, int h){
   if(h == 0){
      return value(); 
   }
   //do some stuff
   alhpa = -alpha;
   beta = -beta;
   int score = search(beta, alpha, h-1);
   //do some more stuff
   return score;
}

Upvotes: 5

Turn
Turn

Reputation: 7020

This has nothing to do with your recursion but rather that what you pass into a function taking a reference must be an lvalue. While a is an lvalue, -a is an rvalue because you've performed an operation on a.

Think about it this way: passing by reference means you might change the value in the function. What does it mean to change -a? It doesn't make any sense from the compiler's point of view.

Upvotes: 1

Related Questions