Does a reference have its own memory address?

I write a code like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<vector>
#include<string>
#include<iostream>
using namespace std;

int main() {

int v=1;
int &r=v;
int *pv=&v;
int *pr=&r;

cout<<pv<<*pv<<endl;
cout<<pr<<*pr<<endl;



return 0;
}


the results of the two output is totally, so it means reference's address is totally the same as its original? why, it do not need a place to store where it is representing??? you know, even a constant has a address.

a reference is not a label functioning like a literal expression when compiling, right?? But if it don't have an address, it loooks like so.


Thanks.
Short answer: no, they don't have their own address

More technical answer: they might have their own address in some circumstances, but you can't access that address in C++


Explanation:

Conceptually, a reference is just an alias for the referred variable. Therefore when you say:
int &r=v;, that means that r "is" v. They're both different names to access the same variable.

Therefore since v and r are the same variable, &v would be equal to &r as your test shows.
Last edited on

the results of the two output is totally,


Totally what? The same?

A reference is the object. You can think of it as another name, an alias, for the exact same object. Not a copy of the object. The exact same object.

In your code, r is another name for v.

Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<vector>
#include<string>
#include<iostream>
using namespace std;

int main() {

int v=1;
int &r=v;
int *pv=&v;
int *pr=&r;

cout<<pv<<*pv<<endl;
cout<<pr<<*pr<<endl;

cout << "v = " << v << endl;
cout << "r = " << r << endl;
v++;

cout << "v = " << v << endl;
cout << "r = " << r << endl;



return 0;
}

Thanks! I come up with another question.

How does C++ store a variable's name and value? does it store the object's name in one place and its value in another place? and then link them together? or the name is a label in the source code, and it always know where to find its value?

or else?
names are irrelevant for the computer. At the end they're discarded and the computation is only done on addresses of each variable
Variables get put at a memory location.

The program accesses those variables by reading/writing that memory location.

The user friendly names that we give our variables do not exist in the compiled program (except for things like debugging symbols, but that's another topic)
Topic archived. No new replies allowed.