#include<iostream>
using namespace std;
int fun(int &x)
{
return x;
}
int main()
{
cout << fun(10);
return 0;
}
Can anyone explain the reason of the error ?
Thanks
On the contrary, your example (const int &)1is incorrect, because It is NOT a "named" object. – Nawaz Nov 29 '11 at 12:19 | Show 10more comments
Temporaries cannot be bound to non-constant references. int(12) is a temporary in this case. – Prasoon Saurav Nov 28 '11 at 9:01 2
To simply answer why the express int & = 12;is invalid, the standard says a string literal is an lvalue, other literals are rvalues. – BruceAdi Nov 28 '11 at 11:41 @curiousguy: Yes. Rvalues are temporary objects, but not all rvalues are temporary object; some are not even objects. – Nawaz Nov 28 '11 at 14:17
Improve this question Follow asked Nov 28 '11 at 8:51 Aquarius_GirlAquarius_Girl 19.2k5959 gold badges195195 silver badges364364 bronze badges 4 5 Temporaries cannot be bound to non-constant references. int(12) is a temporary in this case.
10
is a constant, so you can't pass a reference to it, simply because the whole concept of changing a constant is bizarre.
References were introduced to solve one of the thorny problems in C (and earlier C++), the fact that everything is passed by value and, if you want to have a change reflected back to the caller, you have to pass in a pointer and dereference that pointer within the function to get at the actual variable (for reading and writing to it).
This is something that would be seriously good to have in the next ISO C standard. While having to use pointers may give some of us a lot of rep on Stack Overflow, it's not doing the C programmers of the world much good :-)
The solution to your problem is simple. If you don't need to change the item in the function, just pass it normally:
int fun (int x) { ... }
If you do need to change it, well, then you'll have to pass something that can be changed:
int xyzzy = 10;
cout << fun (xyzzy);
We can shorten this program down to the following:
int& x = 10;
The reason this code doesn't work is because 10 is an rvalue, and rvalues cannot bind to lvalue-references. If that was true, we'd be able to change the value of a literal (which is possible in other languages but not in C++).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With