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; declares y as a reference to x. It effectively means that y becomes another name for x. Any time you use y, it is as if you had said x.
Pointers (not references) are used to store addresses. int& y = &x; is not valid because &x is the address of x (it's an int*). y is a reference to an int, not a reference to an int*.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With