Course outline · 0% complete

0/27 lessons0%

Course overview →

Pass by Value vs Pass by Reference

lesson 4-2 · ~11 min · 10/27

Every function call must answer a question Python never asks you: does the callee receive the caller's actual variable, or its own copy? Get it wrong one way and your function mysteriously changes nothing; get it wrong the other way and you copy a million-element container on every call. C++ makes the choice explicit in the parameter's type, and this lesson is the decision rule professionals use.

By default, C++ copies arguments

void tryToDouble(int x) {   // x is a COPY of the caller's value
    x = x * 2;              // modifies only the copy
}

int main() {
    int score = 50;
    tryToDouble(score);
    std::cout << score;     // still 50
}

This is pass by value. The function gets its own copy, and nothing it does can touch the caller's variable.

Add & to pass by reference

void doubleIt(int& x) {     // x is an ALIAS for the caller's variable
    x = x * 2;              // modifies the original
}

The & after the type makes the parameter a reference: another name for the caller's variable, not a copy. Now doubleIt(score) really changes score. Unit 5 explains how references work under the hood. For now, learn the two behaviors.

caller: score50param x (copy)50by value: new boxcaller: score50param int& xsame box, new name by reference
Pass by value makes a second box holding a copy. Pass by reference gives the function another name for the caller's own box.

Code exercise · cpp

Run this side-by-side demonstration. Same body, one & of difference.

const reference: fast and safe

Copying an int is instant, but copying a std::string of a million characters is real work. Passing big objects by reference avoids the copy, and adding const promises the function will only read:

void printTwice(const std::string& s) {
    std::cout << s << s;
    // s += "!";   would be a COMPILE ERROR, s is const here
}

The rule of thumb professional C++ uses everywhere:

  • Small things (int, double, char, bool): pass by value.
  • Big things you only read: pass by const&.
  • Things the function must modify: pass by &.

Quiz

A function should read a huge std::string without copying it and without being able to change it. Which parameter type is idiomatic?

Code exercise · cpp

Your turn. Complete `swap_ints` so it exchanges the two caller variables. The parameters must be references, otherwise you swap copies and nothing happens. Expected output: `7 3`.