Codiqo

Learn C++ · lesson 24 of 61 · about 9 minutes

References

Give the hero a potion: see that normal parameters are copies, and use a reference so a function can change the caller's variable.

What you'll learn

  • See that normal parameters are copies
  • Change arguments through a reference (&)
  • Pass large values by const reference

A potion by the exit

By the exit lies a potion that heals 30, up to 100. A function drinkPotion can do the adding and the capping, but there's a catch: a normal parameter is a copy, so the function would heal its copy and the hero's real health in main wouldn't change. Writing int& health makes the parameter another name for the caller's variable.

Copies by default

Normally a function gets a copy of each argument, so changes inside it don't reach the caller.

Adding & makes the parameter a reference: another name for the caller's variable. void add_bonus(int& score) changes the real score.

Copy versus reference

#include <iostream>

void by_copy(int score) {
    score += 10;
    std::cout << "the copy became " << score << "\n";
}

void by_ref(int& score) { score += 10; }

int main() {
    int a = 5, b = 5;
    by_copy(a);
    by_ref(b);
    std::cout << a << " " << b << "\n";
}

Output

the copy became 15
5 15

Step through the potion

#include <iostream>

// a potion heals 30, but never above 100
void drinkPotion(int& health) {
    health += 30;
    if (health > 100) {
        health = 100;
    }
}

int main() {
    int health = 85;
    drinkPotion(health);
    std::cout << health << "\n";
}

Output

100

const references

Copying a long string or a big collection costs time. const std::string& s passes it without copying, and const promises the function won't change it. Use it for anything bigger than a number.

swap and a read-only reference

#include <iostream>
#include <string>

void swap_ints(int& x, int& y) {
    int temp = x;
    x = y;
    y = temp;
}

int count_spaces(const std::string& text) {
    int n = 0;
    for (char c : text) if (c == ' ') n++;
    return n;
}

int main() {
    int a = 1, b = 2;
    swap_ints(a, b);
    std::cout << a << " " << b << "\n";
    std::cout << count_spaces("learn to code") << "\n";
}

Output

2 1
2

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.