Make a reference variable point to another variable

5

I have the following question, for example:

int a = 5;
int b = 10;

int & r = a;

How do I make the reference variable r point to b and not more to a ? Is it possible to do this?

    
asked by anonymous 08.09.2015 / 00:22

2 answers

5

Because the variable is a reference and this type is immutable, you can not do it this way. With a pointer you can achieve the same result. After you create a pointer to a , you can point to other addresses. Note that if the pointer has to assign an address directly, then you can not assign it to the variable, you must use the & operator to get its address.

#include <iostream>
using namespace std;

int main() {
    int a = 5;
    int b = 10;
    int *r = &a;
    cout << *r << endl;
    r = &b;
    cout << *r << endl;
    return 0;
}

See working on ideone .

    
08.09.2015 / 00:33
2

This is not possible. Once a reference is initialized it gets tied to that variable until the end of its life. So much so that you can not create a reference without initializing it:

int & r; //Erro de compilação

To do what you want you should use pointers:

int a = 5; int b = 10;

int * r = &a; //r aponta para a

std::cout << *r << std::endl; //Imprime 5

r = &b; //r agora aponta para b
*r = 8; //altera o valor de b através de r

std::cout << b << std::endl; //Imprime 8
    
08.09.2015 / 12:18