Can we reassign the reference in C++?

c++, reference

Solution

`ri = j; // >>> Is this not reassigning the reference? <<<`

No, `ri` is still a reference to `i` - you can prove this by printing `&ri` and `&i` and seeing they're the same address.

What you did is modify `i` through the reference `ri`. Print `i` after, and you'll see this.

Also, for comparison, if you create a `const int &cri = i;` it won't let you assign to that.

Problem

I have read everywhere that a reference has to be initialized then and there and can't be re-initialized again. To test my understanding, I have written the following small program. It seems as if I have actually succeeded in reassigning a reference. Can someone explain to me what is actually going on in my program? ``` #include <iostream> #include <stdio.h> #include <conio.h> using namespace std; int main() { int i = 5, j = 9; int &ri = i; cout << " ri is : " << ri <<"\n"; i = 10; cout << " ri is : " << ri << "\n"; ri = j; // >>> Is this not reassigning the reference? <<< cout << " ri is : " << ri <<"\n"; getch(); return 0; } ``` The code compiles fine and the output is as I expect: ``` ri is : 5 ri is : 10 ri is : 9 ```

Original source