#include <iostream>
using namespace std;
int main ()
{
int x = 0;
int y = 1;
int& z = x;
z = x;
z = y;
cout << "\nx: " << x;
cout << "\ny: " << y;
cout << "\nz: " << z;
return 0;
}
**
EDIT:
**
This code returns 1 for all 3 cases. Shouldn’t this be an error instead?
8.5.3 section of C++ standard says:
A reference cannot be changed to refer to another object after
initialization. Note that initialization of a 2 reference is treated
very differently from assignment to it. Argument passing (5.2.2) and
function value return (6.6.3) are initializations.
No, in your code you aren’t changing what
zreferences, instead you’re changing the contents ofz(and in turn what it references,x).You can see this with the following code:
Both
xandzwill have the value 5, sincezremains a reference tox.