Question

#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

Was it helpful?

Solution

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

OTHER TIPS

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

10 here is a const number and you are trying to create a non const reference to it. Either store 10 in some variable like

int x = 10

then pass it to function or make reference as const.

const int &x

Have it been C++11 then you can also use concept of rvalue reference, so it wont give error.

For more details see error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

A reference (&) must point (reference) to a variable. A constant cannot be referenced.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top