3

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.

5
  • 3
    It's copied. Just because you return a reference doesn't mean the user should be forced to use one. Commented Aug 17, 2013 at 8:12
  • 2
    Try changing a then re-printing p in both your examples. Commented Aug 17, 2013 at 8:13
  • 3
    References are never values. The value of a reference variable or function return is just the referred object. Commented Aug 17, 2013 at 8:22
  • Unless and until you're not referring to the object, use receive the value of the object instead of reference. Commented Aug 17, 2013 at 8:37
  • There is a difference between pointers and reference in C++. What you are returning is not an address but a reference to the global variable. Commented Aug 17, 2013 at 12:09

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, this is pretty much what I wrote, too. ;-)
The question that you asked and the answer that you understood are unrelated.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.