Arvind kr
Arvind kr

Reputation: 101

rvalue not working for reference

I was studying about references and i was trying a program to pass an rvalue to a function as reference argument, like this.

#include<iostream>
using namespace std;

int fun(int &x)
{
    return x;
}
int main()
{
    cout << fun(10);
    return 0;
}

but this didn't work, when i tried to pass an lvalue, It worked.

#include<iostream>
using namespace std;

int fun(int &x)
{
    return x;
}
int main()
{
    int x=10;
    cout << fun(x);
    return 0;
}

can someone explain me why this happens?

Upvotes: 0

Views: 67

Answers (2)

ha9u63a7
ha9u63a7

Reputation: 6862

You are trying to pass reference in your fun(int &x). the & sign means "Passing argument address/reference". Currently you are trying to mix modifiable lvalue and constant rvalue, which is wrong fun(const int &x) will work just fine, this is probably what you want to do. See this

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254751

An rvalue can only bind to an rvalue reference or a const lvalue reference; not to a non-const lvalue reference. So either of these would work:

int fun(int const & x);
int fun(int && x);

This is to prevent surprising behaviour where a function might modify a temporary value instead of the variable you thought it might; for example:

void change(int & x) {++x;}

long x = 42;
change(x);
cout << x;   // would print 42: would have changed a temporary 'int', not 'x'

Upvotes: 6

Related Questions