Home >Backend Development >C++ >Can C References Be Reassigned, or is it Just Value Modification?

Can C References Be Reassigned, or is it Just Value Modification?

Barbara Streisand
Barbara StreisandOriginal
2024-12-05 01:34:11709browse

Can C   References Be Reassigned, or is it Just Value Modification?

Reference Reassignment in C

Declaring a reference in C requires initialization, prompting the impression that references are immutable and cannot be reassigned. However, consider the following program:

#include <iostream>

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';
    return 0;
}

The code compiles successfully and produces the expected output:

ri is : 5
ri is : 10
ri is : 9

Contrary to popular belief, the line ri = j does not reassign the reference ri. Instead, it modifies the value of i through the reference ri, as evidenced by printing i before and after the line. This behavior is supported by the fact that &ri and &i print the same address, indicating that ri remains a reference to i.

In contrast, declaring a constant reference (const int &cri = i) prevents reassignment of the reference itself.

The above is the detailed content of Can C References Be Reassigned, or is it Just Value Modification?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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