C++ References
A reference is another name for an existing variable. It is written with an ampersand after the type: int& r = x; makes r a second name for x. Whatever you do to r happens to x.
Creating a reference
#include <iostream>
int main() {
int x = 10;
int& r = x; // r refers to x
r = 25;
std::cout << "x = " << x << "\n";
x = 40;
std::cout << "r = " << r << "\n";
return 0;
}x = 25 r = 40
A reference must be given its variable when it is created, cannot be empty, and always refers to the same variable.
Pass by reference
Function parameters are normally copies. A reference parameter lets a function change the caller's variable, as in this swap:
#include <iostream>
void swapValues(int& a, int& b) {
int t = a;
a = b;
b = t;
}
void addBonus(int& score, int bonus) {
score += bonus;
}
int main() {
int a = 4, b = 9;
swapValues(a, b);
std::cout << "a = " << a << ", b = " << b << "\n";
int score = 50;
addBonus(score, 10);
std::cout << "score = " << score << "\n";
return 0;
}a = 9, b = 4 score = 60
const references: no copy, no change
Copying a big object such as a long string or a vector costs time and memory. A const reference passes the original without copying, and const promises the function will not change it. This is the standard way to pass anything bigger than a number:
#include <iostream>
#include <string>
#include <vector>
double average(const std::vector<int>& values) {
double sum = 0;
for (int v : values) sum += v;
return values.empty() ? 0 : sum / values.size();
}
void greet(const std::string& name) {
std::cout << "Hello, " << name << "!\n";
}
int main() {
std::vector<int> marks = {70, 85, 90};
std::cout << average(marks) << "\n";
greet("Ravi");
return 0;
}81.6667 Hello, Ravi!
References in loops
for (int& m : marks) m += 5; changes every element through a reference, while for (int m : marks) would only change copies.
A pitfall: returning a reference to a local
Never return a reference (or pointer) to a local variable: the variable is destroyed when the function returns, and the reference then refers to nothing valid. The compiler warns about this.
References or pointers?
Both let code reach another variable. Use references for parameters and loops; use pointers when the target may be absent (nullptr) or may change, which the next topic covers.
Practice exercises
- Write
void triple(int& n)and use it on a variable. - Write a function that returns both the smallest and the largest value of a vector through two reference parameters.
- Add 5 to every element of a vector with a range-based
forand a reference.