0

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?

dragosht
  • 3,237
  • 2
  • 23
  • 32
Arvind kr
  • 103
  • 1
  • 3
  • 12

2 Answers2

6

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'
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

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

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108