By value: the function gets a copy
Normally a function receives a copy of each argument. Changing the copy doesn't change the original:
#include <iostream>
using namespace std;
void addTen(int n) {
n += 10;
cout << "Inside: " << n << "\n";
}
int main() {
int score = 5;
addTen(score);
cout << "Outside: " << score << "\n"; // still 5!
return 0;
}Output
Inside: 15 Outside: 5
By reference: the function uses the original
Put an & after the type and the parameter becomes a reference: another name for the caller's variable. Now changes stick:
#include <iostream>
using namespace std;
void addTen(int& n) {
n += 10;
}
int main() {
int score = 5;
addTen(score);
cout << "Score: " << score << "\n"; // now 15
return 0;
}Output
Score: 15
Think of it like this: By value is giving someone a photocopy of your homework: they can scribble on it, your copy stays clean. By reference is giving them your actual notebook.
A classic: swap
#include <iostream>
using namespace std;
void swapValues(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 1, y = 2;
swapValues(x, y);
cout << "x = " << x << ", y = " << y << "\n";
return 0;
}Output
x = 2, y = 1
const references: fast and safe
Copying a big string or list takes time. A const reference passes the original without copying it, and const promises the function won't change it:
#include <iostream>
#include <string>
using namespace std;
void shout(const string& message) {
cout << message << "!!!\n";
}
int main() {
shout("I love C++");
return 0;
}Output
I love C++!!!
Remember: Small values (
int,double,char): pass by value. Big things you only read (string, vectors): pass byconst&. Things the function must change: pass by&.