Home > Backend Development > C++ > Can C References Be Reassigned, or Is Something Else Happening?

Can C References Be Reassigned, or Is Something Else Happening?

Susan Sarandon
Release: 2024-12-04 22:07:13
Original
403 people have browsed it

Can C   References Be Reassigned, or Is Something Else Happening?

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";
Copy after login

Observations:

  • The code compiles successfully without errors.
  • The output shows that ri initially points to i and then changes to refer to j.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template