The Analogy: The Order Form
A function's parameter list is an order form. Each field has a name, a type, and sometimes a printed default you can leave blank. The caller fills it in; the function reads it and gets to work.
The important detail is what happens at the counter. Hand over a photocopy of your document and the clerk can scribble on it all day without touching your original — that is passing by value. Hand over the original and any changes are permanent — that is passing by reference. Hand over the original but the clerk wears gloves and cannot write — that is const reference.
Almost every parameter you will ever write is one of those three, and choosing correctly is the difference between a fast, clear program and a slow, surprising one.
Syntax or Core Structure
#include <iostream>
#include <string>
#include <vector>
// By value: the function gets its own copy
void byValue(int n) { n = 99; } // caller's variable unchanged
// By reference: the function works on the caller's object
void byRef(int& n) { n = 99; } // caller's variable becomes 99
// By const reference: reads the caller's object, no copy, cannot modify
void byConstRef(const std::string& s) { std::cout << s.size(); }
// Several parameters, evaluated left to right at the call site
double bmi(double weightKg, double heightM) {
return weightKg / (heightM * heightM);
}
// Default arguments -- rightmost parameters only
void log(const std::string& message,
const std::string& level = "INFO",
bool timestamped = true);
int main() {
int x{5};
byValue(x); std::cout << x << "\n"; // 5
byRef(x); std::cout << x << "\n"; // 99
byConstRef("hello"); // literals bind to const&
std::cout << bmi(70.0, 1.75) << "\n"; // 22.86
log("Started"); // uses both defaults
log("Slow query", "WARN"); // overrides one
log("Crashed", "ERROR", false); // overrides both
return 0;
}
void log(const std::string& message, const std::string& level, bool timestamped) {
// Defaults are declared ONCE, in the declaration -- not repeated here
if (timestamped) { std::cout << "[t] "; }
std::cout << level << ": " << message << "\n";
}
Note that the default values appear in the declaration and not in the definition. Writing them in both places is a compile error.
Technical Depth: Cost, const-correctness and Bad Signatures
What a copy actually costs
struct Report {
std::string title; // one heap allocation when copied
std::vector<double> readings; // one allocation plus N element copies
};
void slow(Report r); // copies the string AND every reading
void fast(const Report& r); // copies one address
// With 100,000 readings, called in a loop, the difference is enormous.
The guideline, and the reasoning behind it:
| Parameter | Style | Why |
|---|---|---|
int, double, char, bool, enum | by value | fits in a register; a reference adds indirection |
std::string, std::vector, any struct | const T& | avoids allocations and element copies |
| something you must modify | T& | the caller needs to see the change |
| something optional | const T* | nullptr expresses absence |
| a copy you will mutate and keep | by value | honest, and enables move optimisation |
The dividing line is roughly two machine words. Below it, copying is cheaper than dereferencing; above it, the reference wins.
const is a contract, not a suggestion
void printAll(const std::vector<int>& data) {
for (const int x : data) { std::cout << x; }
// data.push_back(1); // ERROR -- and that error is the point
}
// const also unlocks the call site
void needsConst(const std::string& s);
void needsMutable(std::string& s);
needsConst("literal"); // fine: temporaries bind to const&
needsConst(getName()); // fine: a returned temporary
needsMutable("literal"); // ERROR: cannot bind a temporary
Marking a parameter const does three things at once: it stops you modifying the argument by accident, it tells every reader of the signature that the argument is safe, and it lets callers pass literals and function results. Leaving it off a read-only reference parameter is a small omission that ripples outward.
Signatures that mislead
// BAD: five positional parameters, three of them bool. What does this call mean?
void createUser(std::string name, bool admin, bool active, bool verified, int age);
createUser("Ada", true, false, true, 36); // unreadable at the call site
// BETTER: a struct with named fields
struct UserOptions {
std::string name;
int age{0};
bool admin{false};
bool active{true};
bool verified{false};
};
void createUser(const UserOptions& opts);
createUser({.name = "Ada", .age = 36, .admin = true}); // C++20, self-documenting
Past three or four parameters — and especially with several of the same type — a parameter object beats a parameter list. Adjacent same-typed parameters are also a silent-bug generator: swap two doubles and it still compiles.
Defaults, and their one trap
void connect(const std::string& host, int port = 8080, int timeoutMs = 5000);
connect("localhost"); // both defaults
connect("localhost", 9000); // one override
// connect("localhost", , 1000); // ERROR: cannot skip a middle parameter
connect("localhost", 8080, 1000); // must restate the default to reach past it
Defaults are filled right to left, so you cannot skip one. Two more rules worth knowing: put the parameters most likely to be overridden leftmost, and remember that changing a default value in a header requires recompiling every caller, because the value is substituted at each call site rather than stored in the function.
Overlooked forms
// Unnamed parameter: satisfies an interface without warning about disuse
void onEvent(int /*eventId*/, const std::string& payload) { handle(payload); }
// Array parameters decay to pointers -- the size must come too
double average(const int values[], std::size_t count);
double average(const int* values, std::size_t count); // identical signature
// A function as a parameter, via a lambda and a template
template <typename Predicate>
int countMatching(const std::vector<int>& data, Predicate pred) {
int n{0};
for (const int x : data) { if (pred(x)) { ++n; } }
return n;
}
const int evens = countMatching(data, [](int x) { return x % 2 == 0; });
Leaving a parameter unnamed is the clean way to say "required by the signature, deliberately unused". And passing behaviour as a parameter is what turns one function into a family of them — the mechanism behind every algorithm in <algorithm>.
Real World Example: An Email Sender
#include <iostream>
#include <string>
#include <vector>
struct MailOptions {
std::string to;
std::string subject;
std::string body;
std::string from{"noreply@example.com"};
bool html{false};
int retries{3};
};
struct SendResult {
bool sent{false};
int attempts{0};
std::string error;
};
// const& : reads a struct with four strings, copies none of them
bool validate(const MailOptions& m, std::string& whyNot) { // T& : an output
if (m.to.empty()) { whyNot = "no recipient"; return false; }
if (m.to.find('@') == std::string::npos) { whyNot = "invalid address"; return false; }
if (m.subject.empty()) { whyNot = "no subject"; return false; }
if (m.retries < 1) { whyNot = "retries < 1"; return false; }
whyNot.clear();
return true;
}
// By value: we want our own copy to modify and return
std::string addSignature(std::string body, const std::string& signer) {
body += "\n\n--\n" + signer;
return body;
}
// A pointer parameter says the log is optional
void send(const MailOptions& mail, SendResult& result,
std::vector<std::string>* auditLog = nullptr) {
std::string reason;
if (!validate(mail, reason)) {
result.error = reason;
return;
}
for (int attempt = 1; attempt <= mail.retries; ++attempt) {
++result.attempts;
const bool ok = (attempt >= 2); // stand-in for a real transport
if (auditLog != nullptr) { // check before using
auditLog->push_back("attempt " + std::to_string(attempt) +
(ok ? " ok" : " failed"));
}
if (ok) { result.sent = true; return; }
}
result.error = "all retries exhausted";
}
int main() {
MailOptions mail{
.to = "ada@example.com",
.subject = "Monthly report",
.body = "Figures attached.",
.retries = 2,
};
mail.body = addSignature(mail.body, "Analytics Team");
SendResult result;
std::vector<std::string> log;
send(mail, result, &log); // pass the address to opt in
std::cout << (result.sent ? "sent" : "failed")
<< " after " << result.attempts << " attempt(s)\n";
if (!result.error.empty()) { std::cout << "error: " << result.error << "\n"; }
for (const std::string& line : log) { std::cout << " " << line << "\n"; }
SendResult quiet;
send(mail, quiet); // no log: the default nullptr
std::cout << "silent send: " << (quiet.sent ? "ok" : "no") << "\n";
return 0;
}
Every parameter style in the lesson appears here doing its proper job. MailOptions replaces what would otherwise be six positional parameters, three of which are strings that could be transposed without a compiler complaint — and the C++20 designated initialisers make the call site read like a form. validate takes the mail as const& (read only) and the reason as std::string& (an output the caller must see). addSignature takes the body by value precisely because it wants its own copy to modify and hand back. And auditLog is a pointer with a nullptr default, which is how the logging becomes genuinely optional: the second send call omits it entirely and the function's null check does the rest.
Common Mistakes
- Passing large objects by value out of habit. The copy is invisible in the source and expensive at runtime.
- Omitting
conston a read-only reference, so callers cannot pass literals or temporaries. - Repeating default arguments in both the declaration and the definition — a compile error.
- Defaults on non-rightmost parameters.
- Expecting to skip a middle argument. You must restate the defaults you want to pass over.
- Adjacent same-typed parameters that are easy to transpose. Wrap them in a struct or distinct types.
- More than about four parameters. Group them into an options struct.
- Assuming a fixed evaluation order for arguments: in
f(g(), h()),hmay run first. - A non-const reference parameter that is never modified. It misleads and blocks temporaries.
Best Practices
- By value for small primitives,
const T&for everything larger,T&when you must modify. - Mark every read-only reference parameter
const. - Declare defaults once, in the declaration, and order parameters so the likely overrides come first.
- Replace long parameter lists with an options struct, and initialise it with designated initialisers.
- Use a pointer with a
nullptrdefault for genuinely optional arguments; check it before use. - Take by value when you need your own mutable copy — it is clearer than a reference plus a local copy.
- Leave unused parameters unnamed rather than deleting them from an interface you must match.
Practice Exercises
- Three signatures: Write
incrementthree times — by value, by reference, by pointer — and print the caller's variable after each. Explain in a comment which one you would ship. - Measure the copy: Write a function taking a
std::vector<int>of one million elements by value, then byconst&. Call each a thousand times, time both withstd::chrono, and report the ratio. - Struct over list: Take a function with six positional parameters (two strings, two ints, two bools), convert it to an options struct with sensible defaults, and rewrite three call sites. Note which version you can read without consulting the declaration.