0
Two variables with the same address
I was messing around with the address of operator and it looks like two variables can be stored in the same address, is this true? Here's the code I was fiddling with: #include <iostream> using namespace std; int main() { int m = 2, n = 6; int &x = m; int &y = n; m = ++x; x = ++m; n = ++y; y = ++n; cout << &m << endl << &x << endl; /*outputs: 0x23fe3c 0x23fe3c */ return 0; } How is this possible? Isn't there only one variable allowed per address?
2 Respuestas
+ 7
int &x = m;
here you didn't create a new variable, you just gave another name to variable m. Now you can access the value at the address &m by using m or x.
Same happens in the next line:
int &y= n
One value is stored in memory, and you can access it by using n or y variable names.
m= ++x // x=3,m=3 and another name for m is x, so x=m=3
x=++m // m=x=4
Again... y=n=8
Now you print &m and &x, well yeah, they have the same address... they are not two different variables. It's just one variable with two different names.
These x and y variables are called reference variables.
0
@voja I didn't know about that, thanks. It makes me wonder how many aliases you can give to a single variable.