Home >Backend Development >C++ >Can C References Be Reassigned?
Reassigning References in C
In C , references are often described as immutable bindings to memory addresses. However, a recent question has raised doubts about this understanding. To explore this topic, let's examine the following C program:
#include <iostream> int main() { int i = 5, j = 9; int &ri = i; std::cout << "ri is: " << ri << '\n'; i = 10; std::cout << "ri is: " << ri << '\n'; ri = j; // Is this not reassigning the reference? std::cout << "ri is: " << ri << '\n'; return 0; }
This code compiles successfully, and its output is:
ri is: 5 ri is: 10 ri is: 9
The question arises: doesn't the assignment ri = j; contradict the notion of immutable references?
No, ri is still a reference to i. This can be verified by printing the addresses of ri and i and observing that they are the same.
What has actually occurred is that the ri reference is used to modify the value of i. Assigning a new value to ri would indeed be forbidden, because the reference is immutable and must always point to the same memory location.
For comparison, consider the following code:
const int &cri = i;
This code will not allow an assignment to cri, because it is a reference to a constant. This demonstrates that while references cannot be reassigned to a new memory location, they can still be used to modify the value at the address they refer to, provided that value is mutable.
In conclusion, the ri = j; assignment in the original program is not a reassignment of the reference itself, but rather a modification of the value it references.
The above is the detailed content of Can C References Be Reassigned?. For more information, please follow other related articles on the PHP Chinese website!