Functions and collections · Lesson 7 of 21
References: by value or by reference?
Does a function get a copy or the original, and why const& is everywhere.
When you pass a variable to a function, C++ passes a copy (by value). Changes inside the function hit the copy; the original stays the same. To let the function change the original, pass it by reference with &.
#include <iostream>
void addBonusCopy(int xp) { xp += 50; }
void addBonusRef(int& xp) { xp += 50; }
void swapValues(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int xp = 100;
addBonusCopy(xp);
std::cout << "after copy: " << xp << "\n";
addBonusRef(xp);
std::cout << "after ref: " << xp << "\n";
int x = 1, y = 2;
swapValues(x, y);
std::cout << x << " " << y << "\n";
return 0;
}A reference isn't a new variable: it's another name for the same memory.
Copying an int is cheap; copying a long std::string or a million-element vector isn't. So when a function only reads, pass a `const` reference: no copy, and no accidental changes.
#include <iostream>
#include <string>
#include <vector>
// Reads only: const& avoids copying the whole vector
int total(const std::vector<int>& scores) {
int sum = 0;
for (int s : scores) sum += s;
return sum;
}
int main() {
std::vector<int> scores = {90, 75, 88};
std::cout << total(scores) << "\n";
int lives = 3;
int& alias = lives; // alias and lives are the same int
alias--;
std::cout << lives << "\n";
return 0;
}What's the output?
#include <iostream>
void f(int a, int& b) {
a = a * 10;
b = b * 10;
}
int main() {
int x = 2, y = 3;
f(x, y);
std::cout << x << " " << y << "\n";
}What will this code print?
Exercise
Write void doubleAll(std::vector<int>& v) that doubles every element in place. The program should print 2 4 6.
Expected output: 2 4 6
#include <iostream>
#include <vector>
void doubleAll(std::vector<int>& v) {
for (int x : v) {
x *= 2;
}
}
int main() {
std::vector<int> v = {1, 2, 3};
doubleAll(v);
for (int x : v) std::cout << x << " ";
std::cout << "\n";
return 0;
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.