Step 2 of 5
Pass by reference
References shine as function parameters. A reference parameter is bound to the caller's variable, so the function can change it, without any of C's pointer syntax:
#include <iostream>
#include <string>
void add_suffix(std::string& s, int n) {
s += "#" + std::to_string(n);
}
void split_minutes(int total, int& minutes, int& seconds) {
minutes = total / 60;
seconds = total % 60;
}
int main() {
std::string name = "player";
add_suffix(name, 7);
int m, s;
split_minutes(135, m, s);
std::cout << name << " " << m << ":" << s << "\n";
}
player#7 2:15
Compared with C
In C you'd write void add_suffix(char *s, ...), call it as add_suffix(&name, 7), and use *s inside. With references:
- The parameter is declared
std::string& s. - The call site passes the variable plainly:
add_suffix(name, 7). - Inside,
sis used like a normal variable.
split_minutes shows out parameters with references: the function fills in minutes and seconds for the caller.
The downside
At the call site, add_suffix(name, 7) doesn't show that name might change. Good names (and const& for parameters that don't change, next step) make intent clear. Many teams also prefer returning values (possibly a struct) over out parameters when practical.
std::to_string(n) converts a number to a std::string.
Your turn: write void swap_values(int& a, int& b).