Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid initialization of non-const reference of type 'int&' from a temporary of type 'int'

#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

like image 540
dark_shadow Avatar asked May 27 '13 06:05

dark_shadow


People also ask

Why is (const int &)1 incorrect?

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

Can int 12 be bound to a non-constant reference?

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

Why is the express int & = 12 invalid?

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

Can int(12) be a temporary reference?

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.


2 Answers

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);
like image 182
paxdiablo Avatar answered Oct 15 '22 18:10

paxdiablo


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++).

like image 44
David G Avatar answered Oct 15 '22 19:10

David G