Writing a function in C++ looks familiar if you've seen functions anywhere else, but there's one decision baked into every single parameter you write: does this function get its own copy of the data, or does it get direct access to the original?
A basic function
int add(int a, int b) {
return a + b;
}
int total = add(2, 3);Every function in C++ needs a declared return type, just like variables need a declared type. Use void when a function doesn't return anything at all.
Pass by value: the default, and a copy
void doubleIt(int number) {
number = number * 2;
}
int x = 5;
doubleIt(x);
std::cout << x; // still 5!By default, C++ passes a copy of the argument into the function. Whatever happens to that copy inside the function stays inside the function; the original variable back where it was called from is completely untouched. This surprises a lot of people coming from languages where everything behaves more like a reference automatically.
Pass by reference: working with the original
void doubleIt(int& number) {
number = number * 2;
}
int x = 5;
doubleIt(x);
std::cout << x; // 10Adding that single & to the parameter changes everything: now the function is operating on the real variable, not a copy, so changes made inside it are visible after the function returns.
const reference: the best of both, for bigger data
void printName(const std::string& name) {
std::cout << name;
}For something small like an int, copying is cheap and rarely worth worrying about. For something bigger, like a long string or a large collection of data, copying it every single time a function is called wastes real time and memory. Passing it by reference avoids the copy, and adding const on top promises the function won't accidentally change the original, giving you speed and safety at the same time. This exact pattern, const reference, shows up constantly in real C++ code once you start reading it.
Default parameters
void greet(std::string name = "friend") {
std::cout << "Hello, " << name;
}A rule of thumb worth keeping
Pass small, simple types like int, double and bool by value, since copying them costs almost nothing. Pass anything bigger, like strings, vectors or your own custom objects, by const reference unless you specifically need the function to modify the original.