All lessons

5. Functions

Pass by reference

0 of 5 activities0%

Reading 1

Aliases with &

Open

By default, C++ passes copies (pass by value). Changes to the parameter do not affect the argument.

Add & to a parameter to pass by reference: void bump(int& x). Then x is another name for the caller’s variable, and changes stick.

Use references when a function must update an argument, or to avoid copying large objects later.

void bump(int& x) {
    x = x + 1;
}

int main() {
    int n = 4;
    bump(n);
    cout << n << endl;  // 5
    return 0;
}

Check 2

What changes

Open

After void setZero(int& x) { x = 0; } and setZero(n); what is n?

Fill in 3

Reference marker

Open

In a parameter list, the character that marks a reference is

Try it 4

Swap two ints

Open

Run the swap. Try other starting values.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Write doubleInPlace

Open

Write void doubleInPlace(int& x) that multiplies x by 2. In main, read n, call doubleInPlace(n), print n.

main.cpp
Loading editor…