Learning pathOriginal reference
Lesson 3 of 12

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.

C++23
// 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.

Caller before5
Inside helper15
Caller after5

The parameter is a copy. Changing it leaves the caller’s variable untouched.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

After int score = 90; reset(score); with void reset(int x) { x = 0; }, what is score?

Choose an answer
Try it yourself

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.

C++23
// 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

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.