Learn C++
#include "functions/function_params.hpp"

Parameters & Return Values in C++

//concept

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.

//how it works
1

By value: a private copy

void f(int x) works on a copy — caller data is untouched, but large objects pay a full copy.

2

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.

3

By const reference: read-only view

void f(const std::string& s) is the standard big-input signature: zero copies, zero mutation, full speed.

4

Return safely

Return locals by value (elision makes it free); never return references or pointers to locals — they dangle the moment the function exits.

//example
#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;
}
Output
hi!, 3
1shout takes w by mutable reference, so appending ! modifies the caller's actual string.
2len takes the same string by const reference — read-only, no copy made.
3w is now hi! (length 3), and both print from the single shared object.
//use cases
Passing strings, vectors, and maps as const& in every read-only function
Modifying caller variables through & out-parameters (or returning structs)
Returning big objects by value and trusting elision/moves to keep it free
Auditing reference returns to guarantee they never point at dead locals

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.