Parameters & Return Values in C++
C++ passes arguments three ways, and the choice is the function's contract. Pass by value copies (safe, but costly for big objects and unable to modify the caller). Pass by reference (Type&) aliases the caller's variable (modifiable, no copy). Pass by const reference (const Type&) reads without copying or modifying — the default for large inputs.
Functions return by value (often elided/copied cheaply via RVO and moves), by reference only to data that outlives the call (never a local!), and multiple results via structs, tuples, or out-parameters. Since C++17, guaranteed copy elision makes return-by-value genuinely free in the common cases.
By value: a private copy
void f(int x) works on a copy — caller data is untouched, but large objects pay a full copy.
By reference: the real thing
void f(int& x) aliases the caller's variable — writes persist, reads cost nothing. Use for out-parameters and in-place work.
By const reference: read-only view
void f(const std::string& s) is the standard big-input signature: zero copies, zero mutation, full speed.
Return safely
Return locals by value (elision makes it free); never return references or pointers to locals — they dangle the moment the function exits.
#include <iostream>#include <string> void shout(std::string& s) { s += "!"; }int len(const std::string& s) { return (int)s.size(); } int main() { std::string w = "hi"; shout(w); std::cout << w << ", " << len(w) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.