C++ Function Parameters
Parameters can be passed by value (a copy), by reference (`&`, the original), or by pointer. C++ also supports default parameter values and function overloading based on parameter types.
Choosing pass-by-value vs pass-by-reference matters for both performance (avoiding copies of large objects) and correctness (whether the function should modify the caller's data).
Default parameters
`void greet(std::string name = "Guest")` lets you call `greet()` without an argument, using "Guest" automatically.
Pass by value vs reference
Pass by value copies the argument โ changes inside the function don't affect the caller. Pass by reference (`int&`) shares the same memory, so changes do affect the caller.
void greet(std::string name = "Guest") {
std::cout << "Hello " << name;
}
int main() { greet(); }Hello GuestThe default value is used since no argument was passed.
void square(int& n) { n = n * n; }
int main() {
int x = 4;
square(x);
std::cout << x;
}16Passing by reference lets square() modify x directly.
Key points
- Default parameters provide a fallback value.
- Pass by value copies; pass by reference shares memory.
- Use const T& to pass efficiently without allowing mutation.
- Default parameters must come after non-default ones.
