Return Values
Master function return values to create functions that compute and send data back to the caller
Learn how functions can send data back to their callers and understand how to use return values effectively.
A Simple Example
#include <iostream>
// Returns an int
int add(int a, int b) {
int sum{a + b};
return sum; // Send result back to caller
}
int main() {
int result{add(5, 3)}; // Store returned value
std::cout << "5 + 3 = " << result << "\n";
// Use return value directly
std::cout << "10 + 20 = " << add(10, 20) << "\n";
// Use in calculations
int total{add(100, 200) + add(50, 75)};
std::cout << "Total: " << total << "\n";
return 0;
}
Breaking It Down
Return Type Declaration
- What it does: The return type before the function name tells what kind of value the function sends back
- Common types: int, double, bool, char, or void for no return value
-
Example:
int add(...)promises to return an integer - Remember: The return type must match what you actually return
The return Statement
- What it does: Sends a value back to the caller and immediately exits the function
-
Syntax:
return expression;where expression evaluates to the return type -
Example:
return sum;orreturn a + b; - Remember: Code after return never executes
Using Return Values
-
Store in variable:
int result{add(5, 3)}; -
Use directly:
std::cout << add(5, 3); -
Use in expressions:
int total{add(1, 2) + add(3, 4)}; - Remember: You can use return values anywhere you need that type of data
Multiple Return Paths
- Functions can have multiple return statements for different conditions
- Example: Early returns for validation or edge cases
- Best practice: Every possible path through the function must return a value
- Remember: First return executed ends the function immediately
Why This Matters
- Functions that only print output are limited - they can't be used in calculations, stored in variables, or passed to other functions.
- Return values unlock the true power of functions by letting them compute and deliver results that can be used anywhere in your program.
Critical Insight
Return values make functions composable! You can use the output of one function as input to another, building complex operations from simple building blocks.
Think of functions as LEGO blocks - each returns a piece that can snap into another function. This lets you build sophisticated programs from simple, reusable components:
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
int square(int n) {
return multiply(n, n); // Using multiply to build square
}
// Calculate: (5 + 3)² + (4 + 6)²
int result{add(square(add(5, 3)), square(add(4, 6)))};
// result is 164 (64 + 100)
This is the foundation of functional programming - combining small, focused functions to create powerful operations!
Best Practices
Match return type to purpose: Use bool for yes/no questions, int for counts, double for calculations with decimals.
Return early for validation: Check for invalid inputs at the start and return immediately to avoid deeply nested code.
Use meaningful return values: For main(), return 0 for success, non-zero for errors. For other functions, make return values intuitive.
Avoid multiple returns when possible: While multiple returns are sometimes necessary, prefer a single return point for easier debugging.
Common Mistakes
Forgetting to return a value: Non-void functions must return something. Missing return gives undefined behavior.
Return type mismatch: Returning a double when function expects int causes truncation. Returning int when expecting double is okay.
Unreachable code after return: Code after return never executes. Compilers often warn about this.
Not all paths return: Every possible execution path through a non-void function must hit a return statement.
Ignoring return values: Calling a function but not using its return value wastes computation and may indicate a logic error.
Debug Challenge
This function is supposed to calculate the average of two numbers, but there's a bug. Click the highlighted line to fix it:
Quick Quiz
- Which return type should you use for a function that checks if a number is positive?
- What does this function return when called with
mystery(8)?
int mystery(int x) {
if (x > 10) {
return x * 2;
}
return x + 5;
}
- What happens to code written after a return statement in a function?
Practice Playground
Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once