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

C++ References

What is a Reference?

A reference in C++ is an alias for an existing variable, sharing the exact same memory address as the original, so once created, any change made through the reference directly updates the variable it refers to. Unlike a pointer, a reference cannot be reseated to refer to something else later.

Example: What is a Reference?

cpp
#include <iostream>

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

Modifying Variables via References

Because a reference shares its target's memory location, modifying the reference is indistinguishable from modifying the original variable — there's no separate copy to keep in sync. This makes references useful whenever you want an alternate name for the same piece of data.

Example: Modifying Variables via References

cpp
#include <iostream>

int main() {
	int score = 50;
	int &scoreRef = score;
	scoreRef += 20;
	std::cout << score << std::endl;
	return 0;
}

Pass by Reference

You can pass arguments to functions by reference, which avoids copying large variables or objects and lets the function update the caller's original arguments directly. This is typically faster than passing by value for anything larger than a primitive type.

Example: Pass by Reference

cpp
#include <iostream>

void increase(int &x) {
	x += 1;
}

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

Constant References

If you want the performance benefit of reference passing without letting the function modify your data, pass a const reference. It avoids the cost of copying large objects while still guaranteeing the caller's original value stays untouched.

Example: Constant References

cpp
#include <iostream>
#include <string>

void printName(const std::string &name) {
	std::cout << name << std::endl;
	// name = "Changed"; // compile error
}

int main() {
	printName("Alex");
	return 0;
}

Returning References from Functions

Functions can return references, which is useful for chaining method calls or exposing a modifiable slot inside a container. Be careful never to return a reference to a local variable, since it will dangle and point to invalid memory the instant the function returns.

Example: Returning References from Functions

cpp
#include <iostream>

int scores[3] = {10, 20, 30};

int &getScore(int index) {
	return scores[index];
}

int main() {
	getScore(1) = 99;
	std::cout << scores[1] << 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.