C/C++ Arena

Step 4 of 6

A Result type

Sometimes the caller needs to know why it failed. A small Result type carries either a value or an error message. (C++23 standardizes this idea as std::expected<T, E>.)

struct Result {
    std::optional<int> value;
    std::string error;
    bool ok() const { return value.has_value(); }
};

Your turn: write Result parse_money(const std::string& s) for amounts like "$2700":

Previous: optional for "maybe" Next: Passing errors up