Ch6.4: Returning Values
Overview
A function may produce a value and give it back to the caller using the
return statement. Understanding how return values work is
essential for writing meaningful functions.
In this chapter, you will learn:
- how
returnworks - how to return built‑in types
- how to return objects
- how early returns work
- why returning references is sometimes useful
- why returning references to local variables is always wrong
1. Basic return
A function with a non‑void return type must return a value.
int add(int a, int b)
{
return a + b;
}
The expression after return becomes the value of the function call.
int x = add(3, 4); // x == 7
2. Returning objects
Functions can return objects just like they return integers.
::fast_io::string greet()
{
return ::fast_io::string("Hello from fast_io!");
}
int main()
{
::fast_io::string s = greet();
::fast_io::println(s);
}
Modern C++ performs return value optimization (RVO), so returning objects is efficient.
3. Early return
A function may contain multiple return statements.
The first one that executes ends the function immediately.
int classify(int x)
{
if(x < 0)
return -1;
if(x == 0)
return 0;
return 1;
}
Early returns are often clearer than deeply nested if statements.
4. Returning references
A function may return a reference. This allows the caller to access or modify the original object.
int & max_ref(int & a, int & b)
{
return (a > b) ? a : b;
}
int main()
{
int x{10};
int y{20};
int & r = max_ref(x, y);
r = 100; // modifies y
// x == 10, y == 100
}
Returning references is powerful, but must be used carefully.
5. Never return references to local variables
A local variable is destroyed when the function ends. Returning a reference to it creates a dangling reference.
int & bad()
{
int x{42};
return x; // ❌ ERROR — x is destroyed when the function ends
}
Using such a reference is undefined behavior.
If you need to return a value, return it by value instead:
int good()
{
int x{42};
return x; // ✔ OK — returns a copy
}
6. Returning T const &
Returning a const reference is useful when:
- the object is large
- the object lives longer than the function call
- you want to avoid copying
::fast_io::string const & get_global()
{
static ::fast_io::string g("Hello");
return g; // ✔ OK — static objects live for the entire program
}
Returning a reference to a static object is safe because it never goes out of scope.
Key takeaways
returnends the function and produces a value.- Functions can return built‑in types or objects.
- Early returns improve clarity.
- Returning references allows modifying the original object.
- Never return references to local variables.
- Returning
T const &is useful for large, long‑lived objects.