C/C++ Arena

Step 2 of 6

Status codes

The C-style approach: return a status (success or failure), and deliver the actual result through a reference parameter.

bool try_buy(int& money, int price) {
    if (price > money) return false;
    money -= price;
    return true;
}

Simple and fast, but it's easy for callers to ignore the returned status. [[nodiscard]] makes the compiler warn when they do.

Your turn: write [[nodiscard]] bool divide(int a, int b, int& out) that returns false for division by zero and otherwise stores a / b in out.

Previous: Bugs vs expected failures Next: optional for "maybe"