Created
May 7, 2020 01:14
-
-
Save mshafae/ad1b7439ed928cd7608abd9627ddbe16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
int main(void){ | |
int x = 42; | |
cout << "int x is " << x << " and it is located at " << &x << endl; | |
cout << endl; | |
int* p = &x; | |
cout << "Let's set int* p equal to the address of x..." << endl; | |
cout << "int *p is " << p << " and it is located at " << &p << endl; | |
cout << "By dereferencing p, p points to " << *p << endl; | |
cout << endl; | |
int& r = x; | |
cout << "Let's set int& r equal to x..." << endl; | |
cout << "int& r is " << r << " and it is located at " << &r << endl; | |
cout << "Notice that r (" << &r << ") has the same address as x (" << &x << ")" << endl; | |
cout << "This is very strange since x and r are two different things." << endl; | |
cout << endl; | |
cout << "Let's set p equal to the address of r..." << endl; | |
p = &r; | |
cout << "int *p is " << p << " and it is located at " << &p << endl; | |
cout << "By dereferencing p, p points to " << *p << endl; | |
cout << endl; | |
int y = 17; | |
cout << "int y is " << y << " and it is located at " << &y << endl; | |
cout << endl; | |
cout << "Can I have p point to y?" << endl; | |
p = &y; | |
cout << "int *p is " << p << " and it is located at " << &p << endl; | |
cout << "By dereferencing p, p points to " << *p << endl; | |
cout << "The answer is yes I can!" << endl; | |
cout << endl; | |
cout << "Can I have r bind to y?" << endl; | |
cout << "Let's set int& r equal to y..." << endl; | |
r = y; | |
cout << "int& r is " << r << " and it is located at " << &r << endl; | |
cout << "Notice that r (" << &r << ") has the same address as x (" << &x << ") still!!!!" << endl; | |
cout << "This is very strange since x and r are two different things." << endl; | |
cout << "What just happened? (You can't rebind a reference.)" << endl; | |
cout << "int x was changed to be equal to int y." << endl; | |
cout << "int x is " << x << " and it is located at " << &x << endl; | |
cout << "int y is " << y << " and it is located at " << &y << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment