1. Goals
Choose parameters according to whether a function reads, changes, or accepts missing data.
Distinguish changing a pointed-to object from changing a pointer copy.
State input requirements and keep objects alive for the function call.
2. Prerequisites
You know functions, std::string, copying, references, pointers, nullptr,
and const. You can also distinguish an object's lifetime from its name's scope.
3. Explanation
Start with the function's intent
For a small input such as int, passing by value is usually straightforward:
int withFee(int amount) receives an independent value. Changing amount
does not change the caller's integer. Return a new result and let the caller
decide whether to keep it.
For an existing string that only needs reading, const std::string& name
allows access through a reference without making a string copy as the parameter.
const prevents changes through this reference; it does not freeze every other
alias of the object. This suits printName, but is not a rule that every copy
is expensive or references are always faster. This input choice follows
C++ Core Guidelines F.16.
When an object is required and will be changed, use T&, such as int& points.
addPoints(points, 3) modifies the caller's actual points variable. A valid
reference has no empty state like nullptr; do not manufacture a reference
by dereferencing a null pointer. The object must also be alive during the call.
When having no object is a valid input, you can use T* and explain what
nullptr means. Here, addBonus(nullptr) skips the bonus. Otherwise, the
pointer must refer to a live int that can be modified. Checking for non-null
does not detect dangling pointers. Using a pointer here does not transfer
ownership or authorize the function to release the object.
A pointer copy can still access the original object
An int* points parameter is also passed by value: its address value is copied.
*points += 2 changes the pointed-to object; points = nullptr changes only
the function's local pointer. Consequently, clearLocalPointer(selected)
does not clear the caller's selected pointer. Parameter initialization is
specified in the working draft on function calls.
Similarly, assignment to an int& target parameter changes the referenced
integer; it does not rebind the reference to another integer. Nor does it
change any caller variable of type int*. If the caller should select a
different pointer, a clear approach at this level is to return the new pointer
and let the caller assign it. That is a different task from changing an integer.
Read the position of const
const int amount: prevents changing the function's integer copy; it does not make the caller's variableconst.const int* points: prevents changing the integer through*points, but allows reassigning the local pointer to another location.int* const points: prevents reassigning the local pointer, but still allows modifying the integer through it when valid. It does not protect the pointee.
The caller must keep points and added amounts between 0 and 1000;
these functions do not validate or reject values outside that range. Under
this precondition, the demonstrated additions stay within the range of int.
An & or * does not check numeric limits or lifetimes and cannot replace
input requirements.
4. Runnable example
Save as main.cpp and compile with C++17. No input is required.
#include <iostream>
#include <string>
int withFee(int amount) {
amount += 5;
return amount;
}
void printName(const std::string& name) {
std::cout << "Name: " << name << '\n';
}
void addPoints(int& points, int amount) {
points += amount;
}
void addBonus(int* points) {
if (points != nullptr) {
*points += 2;
}
}
void clearLocalPointer(int* points) {
points = nullptr;
std::cout << "Local pointer cleared: " << (points == nullptr) << '\n';
}
int main() {
std::cout << std::boolalpha;
std::string name{"Mai"};
int points{10};
printName(name);
int quote = withFee(points);
std::cout << "Original: " << points << '\n';
std::cout << "Quote: " << quote << '\n';
addPoints(points, 3);
addBonus(&points);
addBonus(nullptr);
std::cout << "Updated: " << points << '\n';
int* selected = &points;
clearLocalPointer(selected);
std::cout << "Caller still points to points: " << (selected == &points) << '\n';
std::cout << "Through caller pointer: " << *selected << '\n';
return 0;
}Exact output:
Name: Mai
Original: 10
Quote: 15
Updated: 15
Local pointer cleared: true
Caller still points to points: true
Through caller pointer: 15Trace points: withFee leaves it at 10; addPoints changes it to 13;
addBonus(&points) changes it to 15; the nullptr call skips the operation.
selected still points to the live points variable when the last line
reads *selected.
5. Common mistakes
Passing by value and expecting the caller's integer to change automatically.
Adding
const&to everyintbecause references are assumed to be faster.Making a read-only function take
T&, obscuring whether it changes the input.Dereferencing before checking
nullptrin a function that accepts missing data.Assuming assigning
nullptrto aT*parameter changes the caller's pointer.Saving an address or reference for later without checking the object's lifetime.
6. Practice
Change the initial points to
0and keep the calls: expectOriginal: 0,Quote: 5,Updated: 5, and finallyThrough caller pointer: 5.With the original
10points, changeaddPoints(points, 3)toaddPoints(points, 0). ExpectUpdated: 12;addBonus(nullptr)still does nothing.Write
void resetPoints(int& points)that assigns0. Call it with a variable containing12, then print that variable: expect0. Do not use a return value.In a copy of the code, add
name = "An";insideprintName. Compilation must fail becausenameis a read-only reference. Remove the line afterward.
7. Self-check
Why can
addBonuschange points even though its pointer parameter is a copy? Answer: the copied address still refers to the same object;*pointsaccesses it. Assignment topointsitself only changes the pointer copy.Which types suit a required read-only string and a required mutable integer? Answer:
const std::string&for the string andint&for the integer. Both require valid objects while the function uses them.Does
int* const pointsprohibit*points = 0? Answer: no. It prevents reassigning the local pointer;const int*prevents changing the integer through that pointer. Both still require respecting the object's lifetime.
Sample code
Source file
cpp98_foundation/11_parameter_passing/main.cpp
#include <iostream>
#include <string>
int withFee(int amount) {
amount += 5;
return amount;
}
void printName(const std::string& name) {
std::cout << "Name: " << name << '\n';
}
void addPoints(int& points, int amount) {
points += amount;
}
void addBonus(int* points) {
if (points != nullptr) {
*points += 2;
}
}
void clearLocalPointer(int* points) {
points = nullptr;
std::cout << "Local pointer cleared: " << (points == nullptr) << '\n';
}
int main() {
std::cout << std::boolalpha;
std::string name{"Mai"};
int points{10};
printName(name);
int quote = withFee(points);
std::cout << "Original: " << points << '\n';
std::cout << "Quote: " << quote << '\n';
addPoints(points, 3);
addBonus(&points);
addBonus(nullptr);
std::cout << "Updated: " << points << '\n';
int* selected = &points;
clearLocalPointer(selected);
std::cout << "Caller still points to points: " << (selected == &points) << '\n';
std::cout << "Through caller pointer: " << *selected << '\n';
return 0;
}