Return Values

Return Values in C++: Parameters are the coins going in. The return value is what drops into the tray.

The Analogy: The Vending Machine

Parameters are the coins going in. The return value is what drops into the tray.

A good vending machine gives you exactly one thing, and you can see what it is. A bad one takes your money, changes the display, updates a counter somewhere, and maybe dispenses something — you have to inspect three places to find out what happened. Functions have the same failure mode: the ones that communicate through their return value are easy to reason about, and the ones that communicate through side effects are not.

The return type is also a promise printed on the front of the machine. double average(...) tells the caller what to expect before they read a single line of the body.


Syntax or Core Structure

#include <iostream>
#include <string>
#include <vector>
#include <optional>

// Return a value
int square(int n) { return n * n; }

// Return nothing
void log(const std::string& s) {
    if (s.empty()) { return; }          // early exit from a void function
    std::cout << s << "\n";
}

// Multiple returns -- often clearer than one variable assigned in branches
std::string grade(int mark) {
    if (mark >= 90) { return "A"; }
    if (mark >= 75) { return "B"; }
    if (mark >= 60) { return "C"; }
    return "F";                         // every path must return
}

// Return a struct to deliver several values at once
struct Stats { double mean; int min; int max; };

Stats analyse(const std::vector<int>& data) {
    Stats s{0.0, data.front(), data.front()};
    for (const int x : data) {
        s.mean += x;
        if (x < s.min) { s.min = x; }
        if (x > s.max) { s.max = x; }
    }
    s.mean /= static_cast<double>(data.size());
    return s;
}

int main() {
    std::cout << square(7) << "\n";                  // 49
    std::cout << grade(82) << "\n";                  // B

    const Stats s = analyse({4, 8, 15, 16, 23, 42});
    std::cout << s.mean << " " << s.min << "\n";

    // C++17 structured bindings: unpack without repeating "s."
    const auto [mean, low, high] = analyse({1, 2, 3});
    std::cout << mean << " " << low << " " << high << "\n";
    return 0;
}

Note grade returning from four places. Multiple returns used to be discouraged; modern style prefers them, because each one sits next to the condition that justifies it.


Technical Depth: What Actually Comes Back

Returning by value is cheap now

The old advice was that returning a big object copied it, so you should pass an output parameter instead. That advice is obsolete. The compiler performs copy elision: it constructs the returned object directly in the caller's storage, so there is no copy and no move.

std::vector<int> makeRange(int n) {
    std::vector<int> out;               // built directly where the caller wants it
    for (int i = 0; i < n; ++i) { out.push_back(i); }
    return out;                         // no copy -- guaranteed elision territory
}

std::vector<int> nums = makeRange(1000);

Do not write return std::move(out);. Adding std::move here actually defeats the optimisation, because the return expression is no longer a plain name the compiler can elide.

Never return a reference or pointer to a local

This is the single most dangerous return-value bug in C++.

const std::string& broken() {
    std::string local = "hello";
    return local;                       // local dies here -- reference dangles
}

int* alsoBroken() {
    int value = 42;
    return &value;                      // same problem, with a pointer
}

The caller reads memory that has been reclaimed. It often appears to work, which is why it survives testing and fails in production. Returning a reference is only valid when the referent outlives the call: a member of *this, an element of a container the caller owns, or a static.

class Basket {
    std::vector<Item> items;
public:
    Item& at(std::size_t i) { return items[i]; }        // fine -- owned by the object
    const std::vector<Item>& all() const { return items; }
};

Returning "maybe nothing" with std::optional

A lookup that can fail has three bad conventional answers: return a sentinel like -1, return a bool and fill an output parameter, or throw. std::optional<T> says it in the type.

#include <optional>

std::optional<int> parseAge(const std::string& text) {
    try {
        const int n = std::stoi(text);
        if (n < 0 || n > 130) { return std::nullopt; }
        return n;
    } catch (...) {
        return std::nullopt;
    }
}

if (const auto age = parseAge(input)) {
    std::cout << "Age is " << *age << "\n";     // dereference to read
} else {
    std::cout << "Not a valid age\n";
}

The caller cannot forget to check, because reading the value requires unwrapping it.

Return-type choices at a glance

You want to returnWriteWhy
A number or small structint, PointBy value, trivially cheap
A big container you builtstd::vector<T>Elision makes it free
Access to something you ownT& / const T&No copy, referent outlives the call
A result that may not existstd::optional<T>Absence is visible in the type
Success plus a payloadbool + out-param, or a structA struct is usually clearer
Several related valuesA named structBetter than std::pair's .first

Make ignoring the answer an error

If a function's whole purpose is its return value, mark it [[nodiscard]]. The compiler then warns when a caller drops it.

[[nodiscard]] bool saveFile(const std::string& path);

saveFile("data.txt");        // warning: ignoring return value

auto return types

auto deduces the return type from the return statements, which must all agree.

auto half(int n) { return n / 2.0; }        // deduced double

Use it for short helpers and templates. In a public header prefer the explicit type: it is documentation, and it lets callers read the signature without reading the body. Note that bare auto strips references, so auto get() { return member; } returns a copy; write auto& or decltype(auto) if you meant a reference.


Real World Example: A Temperature Log Reader

A small pipeline where every function's return type documents exactly what can happen.

#include <iostream>
#include <string>
#include <vector>
#include <optional>
#include <sstream>

struct Reading {
    std::string station;
    double celsius;
};

struct Summary {
    std::size_t count;
    double mean;
    double hottest;
    std::string hottestStation;
};

// Parsing can fail, so the failure is in the return type.
std::optional<Reading> parseLine(const std::string& line) {
    std::istringstream in(line);
    Reading r;
    if (!(in >> r.station >> r.celsius)) { return std::nullopt; }
    if (r.celsius < -90.0 || r.celsius > 60.0) { return std::nullopt; }
    return r;
}

// Building a container: return it by value, elision handles the cost.
std::vector<Reading> parseAll(const std::vector<std::string>& lines,
                             std::size_t& rejected) {
    std::vector<Reading> out;
    rejected = 0;
    for (const std::string& line : lines) {
        if (const auto r = parseLine(line)) {
            out.push_back(*r);
        } else {
            ++rejected;
        }
    }
    return out;
}

// Several values that belong together -> a named struct, not a pair.
std::optional<Summary> summarise(const std::vector<Reading>& readings) {
    if (readings.empty()) { return std::nullopt; }

    Summary s{readings.size(), 0.0, readings.front().celsius,
              readings.front().station};
    for (const Reading& r : readings) {
        s.mean += r.celsius;
        if (r.celsius > s.hottest) {
            s.hottest = r.celsius;
            s.hottestStation = r.station;
        }
    }
    s.mean /= static_cast<double>(s.count);
    return s;
}

// Pure formatting: takes data, returns text, touches nothing else.
std::string format(const Summary& s) {
    std::ostringstream out;
    out << s.count << " readings, mean " << s.mean
        << " C, hottest " << s.hottest << " C at " << s.hottestStation;
    return out.str();
}

int main() {
    const std::vector<std::string> lines{
        "Leeds 18.5", "York 21.0", "corrupt-row", "Hull 24.5", "Mars 900"
    };

    std::size_t rejected = 0;
    const std::vector<Reading> readings = parseAll(lines, rejected);

    if (const auto s = summarise(readings)) {
        std::cout << format(*s) << "\n";
    } else {
        std::cout << "No usable readings\n";
    }
    std::cout << "Rejected " << rejected << " row(s)\n";
    return 0;
}

Every design decision here is about the return type. parseLine returns std::optional<Reading> because a corrupt row is normal, not exceptional — the caller is forced to handle absence, and there is no magic -999 sentinel to remember. parseAll returns the vector by value rather than filling a caller-supplied reference, because copy elision makes that free and the resulting call site (const std::vector<Reading> readings = parseAll(...)) can be const, which an output parameter would prevent. Its one output parameter, rejected, is a secondary diagnostic rather than the function's purpose, so it stays a reference instead of bloating the return type into a struct. summarise bundles four related numbers into a named Summary instead of a std::tuple, so the reader sees s.hottestStation rather than std::get<3>(s), and it is also optional because there is no meaningful mean of zero readings. format returns a fresh std::string and prints nothing itself, which is what makes it testable: a test can compare its return value against expected text without capturing standard output. And nothing returns a reference or pointer to a local, so there is no dangling to worry about anywhere in the file.


Common Mistakes

  1. Returning a reference or pointer to a local variable. The object dies at the closing brace. Return by value instead.
  2. A non-void function with a path that does not return. Falling off the end is undefined behaviour. Compile with -Wall — the warning is control reaches end of non-void function.
  3. Writing return std::move(local);. It disables copy elision and makes the code slower, not faster. Just return local;.
  4. Sentinel values like -1 or "" for "not found". Callers forget to check, and one day -1 becomes a legitimate result. Use std::optional.
  5. Ignoring a returned status. saveFile(path); with the bool discarded silently loses data. Mark such functions [[nodiscard]].
  6. std::pair for unrelated values. result.first and result.second mean nothing six months later. A two-field struct costs one line.
  7. Returning a bool and mutating three globals. If a caller must inspect other state to learn what happened, the return value is not doing its job.

Best Practices

  • Prefer returning a value to filling an output parameter. It reads better, allows const at the call site, and elision removes the cost.
  • Let the return type encode failure. std::optional<T> for "might be absent", an exception for "should not happen", a status struct when the caller needs a reason.
  • One conceptual result per function. If you need two unrelated things back, that is two functions.
  • Return early. Guard clauses at the top keep the happy path unindented.
  • Use a named struct for grouped results, and unpack it with structured bindings at the call site.
  • Mark pure query functions [[nodiscard]].
  • Spell out the return type in public headers; save auto for short local helpers and templates.

Practice Exercises

  1. Optional lookup: Write std::optional<double> priceOf(const std::vector<Item>&, const std::string& name) that returns std::nullopt when the name is absent. Call it twice — once with a name that exists and once with one that does not — and print a sensible message in both cases.
  2. Struct instead of a pair: Write MinMax range(const std::vector<int>&) returning a struct with min and max fields, then read the result with structured bindings. Decide what the function should do for an empty vector and encode that decision in the return type.
  3. Find the dangler: Write a function that returns const std::string& to a local variable, compile it with g++ -Wall -fsanitize=address, and record both the compiler warning and the runtime report. Then fix it by returning by value and confirm both go quiet.