3

Possible Duplicate:
Is there any way to find the address of a reference?

When we print the address of actual variable and reference variable it shows same address why?

Community
  • 1
  • 1
gurwinder
  • 31
  • 1
  • 1
  • 2
  • It might be less confusing if you don't call it a "reference variable". A reference is not a variable, and doesn't have an address of its own. – Mike Seymour Aug 16 '10 at 15:34
  • 2
    @Mike: Named references are going to be called *variables* in C++0x as discussed [here](http://stackoverflow.com/questions/2908834/why-was-the-definition-of-a-variable-changed-in-the-latest-c0x-draft). – fredoverflow Aug 16 '10 at 15:52

4 Answers4

10

A reference is an alias for another variable - it's just another name for thing that's assigned to the reference.

Behind the scenes the compiler might implement it using pointer mechanics, but if enough is known about the thing being aliased and the lifetime of the reference, the compiler can dispense with that

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
6

Because they're both pointing to the same memory location. That's basically what passing by reference is all about. Instead of passing (copying) the actual value of a variable, the address of it is sent for performance (and memory usage) reasons.

References act kind of like pointers, but they are more safer and differ from pointers in few ways. For more information have a look at this page.

Hamid Nazari
  • 3,905
  • 2
  • 28
  • 31
  • am agry with u but my teacher said that suppose x as an alias for variable a then x must be have some memory address like 01010 and also a can have 0101 so how can both be same – gurwinder Aug 16 '10 at 15:39
  • Internally, a reference is implemented as pointer - so yes, the reference lies somewhere else. But within the rules of the language, x **is** a. I suppose getting the address of a reference is, under the hood, equivalent to getting the value of a pointer (i.e. the adress the pointer stores/points to). –  Aug 16 '10 at 15:48
  • 2
    @gurwinder: Your teacher doesn't know what their talking about. Tell him he's assuming an implementation detail, and C++ is a language, not an implementation. All that's required is what the standard says, you aren't guaranteed a reference *even has storage*. (See §8.3.2/3: "It is unspecified whether or not a reference requires storage".) So by saying "It must have storage somewhere", your teacher is unarguably wrong; it might not. @delnan: It may or may not be, the standard doesn't require anything. – GManNickG Aug 16 '10 at 19:13
5

It is also an important aside to know:

$8.3.2/3 - "It is unspecified whether or not a reference requires storage (3.7).".

Chubsdad
  • 24,777
  • 4
  • 73
  • 129
3

Because it is a reference. Meaning it references the actual variable.

int i = ...;
int& ri = i;

In this example, ri is like an alias for i.

mtvec
  • 17,846
  • 5
  • 52
  • 83