Home >Backend Development >C++ >Can References Be Reassigned in C ?
Understanding Reference Reassignment in C
In C , it's commonly stated that references require initialization upon declaration and cannot be reassigned. However, a recent experiment has raised doubts about this notion. Let's investigate the behavior of reference reassignment in the following 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; // *** Reassignment at Issue *** cout << "ri is : " << ri << "\n"; getch(); return 0; }
The program assigns the reference ri to the integer variable i, making ri an alias for i. Initially, ri points to the value 5. When i is modified to 10, ri correctly reflects this change. However, the critical point is the next statement: ri = j.
Is this not a reassignment of the reference?
The answer, surprisingly, is no. ri is still a reference to i. To demonstrate this, you can compare the addresses of ri and i: they are identical. What you are observing is not a reassignment of the reference but rather a modification of the value stored at the memory location pointed to by ri.
In simpler terms, ri = j is equivalent to *(&ri) = j, where &ri retrieves the memory address of ri and * dereferences it to access the value.
For comparison, if you create a const int &cri = i, it will prevent any reassignment to cri, enforcing its constant nature.
In summary, while references cannot be reassigned to new variables in C , they can be used to modify the value of the object they reference, as seen in our program.
The above is the detailed content of Can References Be Reassigned in C ?. For more information, please follow other related articles on the PHP Chinese website!