C++ References and Memory
In this page:
A Reference Shares the Same Address
A reference is not a separate variable with its own storage; it's another name for the same memory location as the variable it refers to, which can be confirmed by comparing their addresses.
Example: A Reference Shares the Same Address
#include <iostream>
int main() {
int value = 10;
int &ref = value;
std::cout << &value << " " << &ref << std::endl; // same address
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Changing a Reference Changes the Original
Because a reference shares its referent's memory address, modifying the value through the reference immediately changes the original variable too, since there's really only one piece of storage involved.
Example: Changing a Reference Changes the Original
#include <iostream>
int main() {
int value = 10;
int &ref = value;
ref = 50;
std::cout << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
References vs Copies
A reference is fundamentally different from a copy: a copy is a distinct variable at a different memory address holding a duplicated value, while a reference shares the original's address and value entirely.
Example: References vs Copies
#include <iostream>
int main() {
int value = 10;
int copy = value;
int &ref = value;
value = 99;
std::cout << "copy=" << copy << " ref=" << ref << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
References in Function Parameters
Passing a variable by reference to a function lets the function modify the caller's original variable directly, since the parameter shares the same memory address rather than receiving a separate copy.
Example: References in Function Parameters
#include <iostream>
void addTen(int &x) {
x += 10;
}
int main() {
int num = 5;
addTen(num);
std::cout << num << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
References Cannot Be Reseated
Once a reference is bound to a variable at initialization, it can never be made to refer to a different variable afterward -- any later assignment changes the referred-to value, not what the reference points at.
Example: References Cannot Be Reseated
#include <iostream>
int main() {
int a = 1, b = 2;
int &ref = a;
ref = b; // assigns b's VALUE to a, does not rebind ref to b
std::cout << a << " " << b << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: