C++ References
In this page:
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?
#include <iostream>
int main() {
int value = 5;
int &ref = value;
ref = 10;
std::cout << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
int score = 50;
int &scoreRef = score;
scoreRef += 20;
std::cout << score << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
void increase(int &x) {
x += 1;
}
int main() {
int num = 5;
increase(num);
std::cout << num << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 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: