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

dark_shadow picture dark_shadow · May 27, 2013 · Viewed 30.8k times · Source
#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

Answer

paxdiablo picture paxdiablo · May 27, 2013

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);