Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 171 ยท Functions

Returning Values

Return values the modern C++ way - return by value and copy elision, multiple results with structs, pairs, tuples and structured bindings, std::optional, and dangling references.

A function's return value is its answer. In older C++ code you'll often see functions that return nothing useful and write their results through pointer or reference parameters instead, usually because programmers were afraid that returning a big object would copy it. Modern C++ removed that fear. Returning by value is now cheap, clear and the default you should reach for.

This lesson covers everything about getting results out of a function: how return works, why returning a std::vector by value doesn't copy it (copy elision and moves), how to return several values at once with a struct, std::pair or std::tuple and unpack them with structured bindings, how to say "there may be no result" with std::optional, and the one mistake you must never make: returning a reference to a local variable. It builds on Functions and Parameters.

How return works

A return statement ends the function immediately and hands a value back to the caller. The value is converted to the declared return type, just like initializing a variable of that type:

C++ return ends the function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A few rules worth knowing precisely:

  • A void function may use a bare return; to leave early, or simply fall off the end.
  • A non-void function must return a value on every path. Falling off the end of one is undefined behavior. GCC warns with -Wall ("control reaches end of non-void function"); treat that warning as an error.
  • main is the one exception: falling off its end is the same as return 0;.
  • You can let the compiler deduce the return type with auto: auto square(int x) { return x * x; } returns int. All return statements must then deduce the same type. Use this for short helpers and templates; spell the type out when it documents the interface.

Return by value is cheap: copy elision and moves

Consider a function that builds a vector of a million numbers and returns it. Does the caller get a copy of all those elements? No. C++ has two mechanisms that make this efficient.

Copy elision. When a function returns a temporary (a "prvalue"), as in return std::vector<int>(n);, C++17 guarantees that no copy or move happens. The object is constructed directly in the caller's variable. When a function returns a named local variable (return result;), compilers are allowed to do the same thing, called the named return value optimization (NRVO), and in practice GCC, Clang and MSVC do it whenever the function returns that one variable.

Implicit move. When elision doesn't happen, a returned local variable is treated as an rvalue, so it's moved rather than copied. For a vector, a move just transfers three pointers.

You can watch this happen with a type that prints when it is copied or moved:

C++ Watching copy elision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

([[maybe_unused]] just tells the compiler not to warn that t1, t2 and t3 are never read.) The first two calls construct exactly one object and never copy it. The third prints COPIED. The expression first ? a : b is not just the name of a local variable, so the automatic move doesn't apply. The fix is to write two separate returns: if (first) { return a; } return b;, which moves (or elides).

Don't write return std::move(local);. It looks like an optimization but is the opposite: it prevents NRVO, forcing a move where there would have been nothing. GCC even warns about it with -Wpessimizing-move. Just return local;. You'll learn what std::move really does in Move Semantics.

The practical rule: return results by value. Prefer std::vector<int> load_scores() over void load_scores(std::vector<int>& out). The value version is easier to read, can't be called with a half-filled vector, and lets you write const auto scores = load_scores();.

Returning several values

A function has one return type, but that type can bundle several values.

With a struct (usually the best choice)

A small struct gives each value a name, which makes both the function and its callers self-documenting:

C++
struct MinMax {
    int min;
    int max;
};

MinMax min_max(const std::vector<int>& values);

With std::pair and std::tuple

For quick helpers, std::pair<A, B> (from <utility>) holds two values and std::tuple<A, B, C, ...> (from <tuple>) holds any number. They save you from declaring a struct, at the cost of meaningless names (first, second, std::get<2>(t)). You'll study them in depth in std::pair and std::tuple.

Unpacking with structured bindings

Structured bindings (C++17) unpack any of these in one line: auto [a, b] = f();. They work with structs, pairs, tuples and arrays:

C++ Three ways to return several values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

return {lo, hi, ...}; builds the return type from a braced list, so you don't repeat Stats inside the function. The names in a structured binding are your choice and don't have to match the struct's member names; they're matched by position.

Use a struct when the values have meaning beyond this one call, when there are more than two or three of them, or when they're the same type (two ints in a pair are easy to swap by mistake). Use a pair or tuple for short-lived, obvious results like quotient and remainder.

"Maybe a result": std::optional

Many functions can fail to produce a result: a search that finds nothing, a parse of bad text, a lookup of a missing key. Old C++ code signals this with magic values like -1, nullptr or an empty string. Magic values have problems: callers forget to check, and sometimes every value is valid (what should "find the smallest temperature" return when -1 is a real temperature?).

std::optional<T> (C++17, from <optional>) holds either a T or nothing. The type itself tells callers they must check:

C++ std::optional for a search that can fail

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The everyday operations:

Operation Meaning
if (opt) / opt.has_value() Is there a value?
*opt, opt->member Access the value (undefined behavior if empty!)
opt.value() Access the value, throws std::bad_optional_access if empty
opt.value_or(fallback) The value, or fallback if empty
opt.transform(f) (C++23) Apply f to the value if there is one

The if (auto found = ...) form declares the variable and tests it in one step, and keeps found scoped to the if. std::optional is for "no result, and that's normal". When you need to explain why something failed, C++23's std::expected<T, E> carries either a value or an error; see std::optional, std::variant, std::any and std::expected.

Never return a reference to a local

A function can return a reference (int&, const std::string&). That's useful when the referenced object outlives the call: an element of a container passed in, a member of an object, a global. But local variables are destroyed when the function returns, so a reference or pointer to one dangles:

C++
const std::string& make_greeting(const std::string& name) {
    std::string result = "Hello, " + name;
    return result;   // BUG: result dies here; the caller gets a dangling reference
}

GCC catches this simple case ("reference to local variable 'result' returned"), but not every case. Using a dangling reference is undefined behavior: it may appear to work, print garbage, or crash. The fix is simple: return std::string by value.

Returning a reference is correct when the object comes from the caller:

C++ Returning a reference that stays valid

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Even here, be careful: the reference becomes invalid if the vector is destroyed or reallocates (for example, after push_back). There's another subtle trap: if a function takes const T& and returns that same reference, calling it with a temporary returns a reference to an object that dies at the end of the statement. When in doubt, return by value.

The [[nodiscard]] attribute

Some results are easy to ignore by mistake, like an error code or the new value from a function that doesn't modify its input. Mark such functions [[nodiscard]] and the compiler warns when a caller throws the result away:

C++
[[nodiscard]] std::optional<int> parse_port(std::string_view text);

parse_port("8080");   // warning: ignoring return value ... declared with attribute 'nodiscard'

Standard library functions like std::vector::empty() are marked this way, which catches the classic mistake of writing v.empty(); when you meant v.clear();.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. std::vector<int> make() { std::vector<int> v(1'000'000); return v; } What happens to the million elements when you write auto data = make();?

    A returned local variable is elided (NRVO) or, failing that, moved. A vector move just transfers its internal pointers, so nothing is copied.
  2. 2. Why is return std::move(result); worse than return result; for a local variable?

    NRVO only applies when you return a plain name. std::move turns it into an expression, so the compiler must move. GCC warns with -Wpessimizing-move.
  3. 3. auto [q, r] = std::pair{17 / 5, 17 % 5}; What are q and r?

    Integer division gives 3 and the remainder is 2. Structured bindings unpack by position, so q gets first and r gets second.
  4. 4. What is the problem with const std::string& name() { std::string s = "Ada"; return s; }?

    s is a local variable. Returning a reference to it leaves the caller with a reference to a destroyed object, which is undefined behavior. Return std::string by value.
  5. 5. Which is the most expressive way to write a lookup that may find nothing?

    std::optional makes "no result" part of the type, so callers can't mistake it for a real value and are pushed to check.

Summary

  • return ends the function and converts the value to the return type. Every path of a non-void function must return (except main).
  • Return by value. C++17 guarantees elision for temporaries; returned local variables get NRVO or an automatic move. Don't wrap them in std::move.
  • Return several values with a struct (best for named, lasting results), std::pair or std::tuple, and unpack them with structured bindings auto [a, b] = f();.
  • Use std::optional<T> for "maybe a value" instead of magic values; check with if (opt) and use value_or for fallbacks.
  • Never return a reference or pointer to a local variable. Return references only to objects that outlive the call.
  • Mark results that must not be ignored with [[nodiscard]].

Next: Function Overloading, where several functions share one name and the compiler picks the best match.