Codiqo

Learn C++ · lesson 25 of 61 · about 10 minutes

Project: The Merchant

Add a merchant to the adventure with a buy function that takes the gold by reference, has a default price, and returns whether the sale happened.

What you'll learn

  • Split work into small functions
  • Return several results through references
  • Combine a return value, a reference and a default

A merchant at the exit

Just outside the cave, a merchant sells a map for 10 gold and a lantern for 20. Buying is the same job twice, so it's a function, bool buy(int& gold, int price = 10), and it uses everything from this unit:

  • int& gold lets it take the money out of the hero's real gold
  • price = 10 is the usual price, so buy(gold) buys a map
  • the bool it returns tells main whether there was enough, so main can say what happened

The merchant with 25 gold

#include <iostream>

// pays for something if there's enough gold, and says whether it did
bool buy(int& gold, int price = 10) {
    if (gold < price) {
        return false;
    }
    gold -= price;
    return true;
}

int main() {
    int gold = 25;
    std::cout << "A merchant sells maps and lanterns.\n";
    if (buy(gold)) {
        std::cout << "You buy a map. Gold: " << gold << "\n";
    } else {
        std::cout << "You can't afford a map.\n";
    }
    if (buy(gold, 20)) {
        std::cout << "You buy a lantern. Gold: " << gold << "\n";
    } else {
        std::cout << "You can't afford a lantern.\n";
    }
}

Output

A merchant sells maps and lanterns.
You buy a map. Gold: 15
You can't afford a lantern.

Tip

A function can return only one value. Here the value says yes or no, and the change to the gold travels back through the reference, so the caller gets both.

Now try it yourself

This lesson is free in Codiqo, with 8 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.