Make a reference variable point to another variable

Asked

Viewed 214 times

5

I have the following question, for example:

int a = 5;
int b = 10;

int & r = a;

How do I use the reference variable r point to b and no longer to a? It is possible to do this?

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

2 answers

6

As the variable is a reference and this type is immutable, there is no way to do it this way. With a pointer you can get the same result. After creating a pointer to a, it is possible to point to other addresses. Note that in the case of pointer you have to assign an address directly, then you cannot assign to the variable, you have to use the operator & to get her 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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • When you do r = b you’re just assigning to r the value of b. If you read the variable a will see that she too has been changed, because the reference points to her.

  • @C.E.Gesser You’re right. I started answering like this and then I did the naive test and saw that "I could" do it this way. You were already asleep :) Now yours is wrong because you cannot use the pointer in simple variable assignment.

  • True, we make these examples head on and always escapes something. Thanks.

2

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

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

To do what you want you must 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.