mercredi 7 novembre 2018

Why does my variable change according to its reference and not the other way round?

I am new to C++. I am typing in the following commands (please assume I have already included the relevant header files, namespace std and main() function) -

int i, &ri =i;
i = 5; ri = 10;
cout << i  << " " << ri << endl;

The result I am getting is: 10 10

My logic is the following -

  1. &ri refers to i, so the initial value of ri is equal to i (whatever that is).
  2. Now, when I assign the value 5 to i, then the value of ri changes to 5.
  3. Now, when I change the value of ri to 10, then the reference of ri to i is removed and it now occupies a unique space with the value 10 and is no longer linked to i.
  4. Therefore, now when I cout << i and << ri, the result should display 5 and 10.

Instead it seems that i is referring to ri (I checked by changing the values that I assign to ri).

Can you please let me know what I am thinking incorrectly?

Aucun commentaire:

Enregistrer un commentaire