|
I was trying to figure out how & work, so I wrote the following code
#include <iostream>
using namespace std;
void print(int &);
int main()
{
int i = 10;
int &t = i;
cout<<"t = "<<t<<endl;
cout<<"&t = "<<&t<<endl;
cout<<"&i = "<<&i<<endl;
print(t);
cout<<"t = "<<t<<endl;
return 0;
}
void print(int &x)
{
x = 6;
cout<<"x = "<<x<<endl;
}
The output is:
x = 10
&x = 0012FF7C
&i = 0012FF7C
x = 6
i = 6
My questiont is:
int &t = i; what is this line of code doing?
Assigning an integer value to the address of t?
Also, I modified the print() a little bit like this:
void print(int x)
{
x = 6;
cout<<"x = "<<x<<endl;
}
Here is the new output:
x = 10
&x = 0012FF7C
&i = 0012FF7C
x = 6
i = 10
To me, it looks like the modified code is passing by value and the original one is passing by reference. But my question is, in the modified code, I did say "int &t = i;" and I passed t to print(int x). How could a function takes an int as a parameter accept an reference?
Thank you very much for your help!
|
|
|
|
|
|
|
// |