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
}
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