Copies, references, and side effects
Predict whether a function can change its caller by reading its parameter types.
A value parameter is independent
void incrementCopy(int value) receives a separate integer value. Assigning to value does not assign to the caller’s integer. A result-returning alternative, int increased(int value), lets the caller explicitly choose x = increased(x). Calling increased(x) without using the result leaves x unchanged.
Passing small scalar values is a useful default. It keeps mutation visible at the call site and makes independent calls easier to reason about.
A reference names the same object
int& value is a reference parameter: another name for the caller’s integer. Modifying it changes that original object. The ampersand belongs in the declaration; the call remains increment(x).
An ordinary non-const int& needs a suitable modifiable int object. increment(8) and increment(x + 1) are not valid calls for that interface. A const reference permits reading through that parameter but forbids writing through it.
// Complete C++23 program. No input; output: 8 9
#include <iostream>
void incrementCopy(int value) { ++value; }
void increment(int& value) { ++value; }
int main() {
int x = 8;
incrementCopy(x);
std::cout << x << ' ';
increment(x);
std::cout << x << '\n';
}Make mutation part of the contract
Use a mutable reference when changing the caller is the helper’s promised job, such as ordering two values. Use a temporary during a swap so the first assignment does not destroy a value still needed by the second.
Multiple output references can accidentally refer to the same object. A min/max helper that writes two independent results should require distinct output variables that do not alias input array elements. const restricts this access path; it does not freeze every other alias in the program.
Value or reference?
The helper executes x += 10. Compare the caller’s value before and after the call.
The parameter is a copy. Changing it leaves the caller’s variable untouched.
Guided simulation · Change the inputs to test your understanding.
After int score = 90; reset(score); with void reset(int x) { x = 0; }, what is score?
Turn the idea into code
Write orderPair(int& a, int& b) so the caller’s smaller value comes first. Test 9 2, equal values, and two negative values.
Give me a hint
Swap only when a > b; preserve the old a in a temporary before assigning.
Show the explained solution
If a is already no greater than b, the contract is satisfied. Otherwise the swap reverses the two values without losing either one. The helper has O(1) time and auxiliary space.
// Complete C++23 program. Input: two integers.
#include <iostream>
void orderPair(int& a, int& b) {
if (a > b) {
int temporary = a;
a = b;
b = temporary;
}
}
int main() {
int a = 0, b = 0;
std::cin >> a >> b;
orderPair(a, b);
std::cout << a << ' ' << b << '\n';
}Your notes
Mark complete when you can explain it yourself.