Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rvalue and Lvalue References

Tags:

c++

c++11

I have a function printInt like below.

void printInt(const int& a)
{
    cout<<a<<endl;
}

When I call like function using the following arguments like

int a=5;
printInt(a);
printInt(5);

It works perfectly. But when I change the function definition to

void printInt(int& a)
{
    cout<<a<<endl;
}

This gives error to the call printInt(5). Now my question is why const int& is both a lvalue and rvalue reference whereas int& is only a lvalue reference. As far as I know int&& is a rvalue reference. So how a single & can refer to an rvalue reference?

To summarize my problem:

  1. Lvalue reference parameter

    void printInt(int& a)
    {
        cout<<a<<endl;
    }
    
  2. Rvalue reference parameter

    void printInt(int&& a)
    {
        cout<<a<<endl;
    }    
    
  3. Both lvalue and rvalue. but how?

    void printInt(const int& a)
    {
        cout<<a<<endl;
    }
    
like image 734
Avirup Mullick Avatar asked Jan 09 '23 00:01

Avirup Mullick


1 Answers

const int& is an lvalue reference. The thing is that the language specifies that it can bind to rvalues. int& is also an lvalue reference, but it cannot do that. That is why the first version works and the second doesn't.

like image 135
juanchopanza Avatar answered Jan 15 '23 01:01

juanchopanza