c++type-conversionvalue-categories

why incorrect convertion of long long to int causes the compiler to error: cannot bind non-const lvalue to an rvalue


My code is given below.
I understand I can't convert long long to int&, but why does the error say "cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’"?
Is it possible that in some cases, the compiler will treat a type-mismatched expression as an rvalue?

The code:

#include <iostream>
using namespace std;

void func(int& param)
{
    cout << param << endl;
}

int main()
{
    long long param;
    func(param);
    return 0;
}

The compiler error is:

10:10: error: cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
10 |     func(param);
   |          ^~~~~
 3 | void func(int& param)
   |           ~~~~~^~~~~

Solution

  • The function expects a reference to an int variable, but you pass it a long long instead, so the compiler creates a temporary int to assign the long long value to. That temporary is an rvalue, and a non-const reference cannot bind to an rvalue, hence the error.

    Add const to the parameter and then the code will work. A const reference can bind to an rvalue.

    void func(const int& param)
    {
        cout << param << endl;
    }
    

    Or, get rid of the reference and just pass the int by value.

    void func(int param)
    {
        cout << param << endl;
    }