← Back to C++ Course | Chapter 7: Pointers & References | Lesson 8 of 11

C++ References and Memory

A reference is an alias sharing the same memory address as the variable it refers to, so both names access the identical underlying storage, unlike a copy which occupies separate memory.

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

cpp
#include <iostream>

int main() {
	int value = 10;
	int &ref = value;
	std::cout << &value << " " << &ref << std::endl; // same address
	return 0;
}

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

cpp
#include <iostream>

int main() {
	int value = 10;
	int &ref = value;
	ref = 50;
	std::cout << value << std::endl;
	return 0;
}

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

cpp
#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;
}

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

cpp
#include <iostream>

void addTen(int &x) {
	x += 10;
}

int main() {
	int num = 5;
	addTen(num);
	std::cout << num << std::endl;
	return 0;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.