Aquarius_Girl
Aquarius_Girl

Reputation: 22936

Can one reference be assigned different values at different locations?

#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.

Upvotes: 1

Views: 306

Answers (4)

wills
wills

Reputation: 91

z = x
z = y

does not change the reference but the value of x.

Upvotes: 2

kingcong3
kingcong3

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

Zubizaretta
Zubizaretta

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

DRH
DRH

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

Related Questions