Reputation: 59
I was searching for explanations over reference variables in c++ and I found this:
#include<iostream>
int a=10; //global 'a' so that fun doesn't return a reference of its local variable
int & fun();
int main()
{
int p = fun(); //line to be noted
std::cout << p;
return 0;
}
int & fun()
{
return a;
}
This worked and so does this:
#include<iostream>
int a=10; //global 'a' so that fun doesn't return a reference of its local variable
int & fun();
int main()
{
int &p = fun(); //line to be noted
std::cout << p;
return 0;
}
int & fun()
{
return a;
}
My question is how could an integer variable store the value of reference as is being done in first code snippet [line number 6]. Isn't the correct syntax as depicted in code snippet 2 [at line 6], i.e. we should define a reference variable (int &p) to carry the reference and not a regular integral variable? Shouldn't the compiler give an error or at least a warning? I am using GCC 4.7.1 64-bit.
Upvotes: 3
Views: 188
Reputation: 59
Okay got it ... @chris : you were right..When I did this:
int p = fun();
p++;
std::cout << p << endl << a;
It showed the results to be 11 and 10. Hence only a's value is copied into p and p doesn't became the alias of a. But when I tried the same with second code, it showed values of both a and p to be 11. Hence p became the alias of a.
Upvotes: 2
Reputation: 53155
No, it is fine either way.
The return value reference is not even necessary in this special case because you are not trying to modify the return value "on the fly" or the 'a' later, like when you use arithmetic operator overloads for that purpose, for instance
Upvotes: 0