Basic Pointers/References Help

I'm looking at a practice test for my programming class and can't seem to follow references/pointers very well.

I'm a bit of a C++ noob, can someone here explain how the following code actually works and stores information/values? (Specifically the stuff marked line 1-5)

*Some of the lines have a "none of the above option".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main(){

long l = 123;
long *p_l;
long &r_l = l;
p_l = &r_l;

cout << boolalpha;
cout << p_l << endl; // Line 1
l = 789;
cout << *p_l << endl; //Line 2
r_l = 91011;
cout << p_l << endl; // Line 3
cout<< l << endl; //Line 4
cout << (p_l == &r_l) << endl; // Line 5
}
Last edited on
long l = 123; creates an object of type long with automatic storage duration, the name l, and the value 123.

long *p_l; creates an object of type pointer-to-long, with automatic storage duration, the name p_l, and undefined value

long &r_l = l; does not create any objects: this associates the name r_l with the object already called l

p_l = &r_l; creates a pointer to l (or to r_l - they are the same thing) and replaces the former undefined value held in p_l with this new pointer value.

So you have one object of type long (with value 123) which can be referred to in three different ways: by the name l, by the name r_l, and by indirection through pointer, as *p_l

lines 1 and 3 print the pointer value stored in p_l (the address of that long)
line 2 prints the value of the long object (which is 789 by then)
line 4 also prints the value of the same long object (which is 91011 by then)
line 5 compares the pointer value stored in p_l with &r_l, which was the same exact value stored in p_l earlier, so it prints true
Last edited on
First you can see, the variable r_l takes the address of the variable l (reference). So doing this :
p_l = &r_l;
Also it's equivalent to :
p_l = &l;

Line 1 : Prints p_l's value (p_l currently is carrying the address of the variable l)

Line 2 : Uses the value of the variable p_l as an address, and prints the value (789)

Line 3 : Same as line 1, the result still stays the same

Line 4 : Prints the value of the variable l (91011)

Line 5 : Compares the value of the variable p_l with the address of the variable [r_l]. It's always true.
Last edited on
Thanks guys :]
Topic archived. No new replies allowed.