So I am attempting to learn C++ and I have come across something that puzzles me slightly. I have the code,
int x = 0;
int &y = x;
cout << &x<< " " << x << " " << &y << " " <<y<< endl;
This compiles fine and results in:
0 003AFA08 0 003AFA08
What I have trouble understanding why the conversion of x, an int, to &y, a reference, doesn’t result in an error. At first I thought it was some sort of conversion however,
int &y = &x;
results in an error.
Can anyone explain why this works in this way? Thanks in advance.
int&is not an address. It is a reference.int& y = x;declaresyas a reference tox. It effectively means thatybecomes another name forx. Any time you usey, it is as if you had saidx.Pointers (not references) are used to store addresses.
int& y = &x;is not valid because&xis the address ofx(it’s anint*).yis a reference to anint, not a reference to anint*.