Can References Be Reassigned in C ?
In C , references are often touted as immutable entities that must be initialized once and for all. However, a recent code snippet has raised questions about this principle.
Code Snippet:
int i = 5, j = 9; int &ri = i; cout << "ri is : " << ri << "\n"; i = 10; cout << "ri is : " << ri << "\n"; ri = j; cout << "ri is : " << ri << "\n";
Observations:
Question:
Does this code truly reassign the reference ri or is something else happening?
Answer:
No, ri is still a reference to i. The apparent reassignment is actually a modification of i through the reference ri.
Explanation:
When a reference is declared (e.g., int &ri = i), it binds to the object (i in this case) and remains linked to it throughout the program. The code ri = j does not reassign ri but rather modifies the value of i through the reference ri.
To prove this, one can print the addresses of ri and i using &ri and &i, which would show they remain the same. Additionally, if ri were reassigned to j, it would no longer be possible to modify i through ri, which is not the case in the given code.
Conclusion:
While references appear to be reassignable in the code snippet, they are not. Instead, they indirectly modify the object to which they refer. Const references (e.g., const int &cri = i) prevent such modifications and enforce true immutability.
The above is the detailed content of Can C References Be Reassigned, or Is Something Else Happening?. For more information, please follow other related articles on the PHP Chinese website!