Reputation: 22936
#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;
}
**
** 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.
Upvotes: 1
Views: 306
Reputation: 193
{ int x = 0; // Let x be located at memory 0x1234
int y = 1; // Let y be located at memory 0x5678
int& z = x; //There is a variable call z that is a reference to x.
//That is z refers to the same memory location and thus the same content.
z = x; //Set the contents of z to the content of x.
//Since z is currently a reference to x this essentially does nothing.
z = y; //Set the contents of z to the content of y which is the
//same as set the contents of memory 0x1234 to the contents of memory 0x5678.
cout << "\nx: " << x; //print the contents of memory 0x1234
cout << "\ny: " << y; //print the contents of memory 0x5678
cout << "\nz: " << z; //print the contents of memory 0x1234
return 0;
}
It is not giving you an error since you are not changing any memory pointers, but instead, their contents
Upvotes: 1
Reputation: 157
No, that won't generate an error. As mentioned, assigning values to z is the same as assigning values to what it refers to, which in this case is x.
In this case, the standard mandates that z HAS to REFER to x. z cannot be made to refer to some other variable.
Upvotes: 1
Reputation: 8356
No, in your code you aren't changing what z
references, instead you're changing the contents of z
(and in turn what it references, x
).
You can see this with the following code:
x = 5;
cout << x;
cout << z;
Both x
and z
will have the value 5, since z
remains a reference to x
.
Upvotes: 6