A reference is an alias — another name for an existing variable. Created with &. Both names refer to the same memory location.
#include <iostream>
using namespace std;
int main() {
int x = 10;
int &ref = x; // ref is an alias for x
cout << x << endl; // 10
cout << ref << endl; // 10
ref = 99;
cout << x << endl; // 99 (x changed through ref)
return 0;
}
Output:
10
10
99
Pass by Reference
By default, C++ passes arguments by value (a copy). Using & in a parameter passes the original variable — changes persist after the function returns.
void addTen(int &n) { // reference parameter
n += 10;
}
int main() {
int score = 50;
addTen(score);
cout << score; // 60 — original was modified
}
// Swap function using references
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int x = 5, y = 10;
swap(x, y);
cout << x << " " << y; // 10 5
const References
Use const & to pass large objects efficiently without allowing modification:
void print(const string &s) {
cout << s << endl;
// s = "change"; // ERROR — const prevents modification
}
print("Hello World"); // no copy made, no modification allowed
Best Practice: Pass strings and large objects by const& to avoid expensive copies. Pass small types like int and double by value.
Exercise
Write a function square(int &n) that squares the value in place (modifies the original). Test it.
Show Solution
#include <iostream>
using namespace std;
void square(int &n) {
n = n * n;
}
int main() {
int x = 7;
square(x);
cout << "Squared: " << x << endl; // 49
return 0;
}
Quiz
A reference variable is:
A) A copy of another variable
B) An alias that points to the same memory
C) A pointer that needs dereferencing
D) A const variable
Answer
B) A reference is an alias — it shares the same memory address as the original variable.
How do you declare a reference parameter in a function?
A) int *n
B) ref int n
C> int &n
D) &int n
Answer
C) int &n
Summary
A reference is an alias for another variable, using &.
Pass by reference allows functions to modify the caller's variables.
const & passes efficiently without allowing modification.