Return Values
Overview
If Parameters are the Inputs to a function, Return Values are the Outputs.
Very often, a function needs to calculate complex logic and then hand the final answer back to the main program so it can be used in further equations. By defining a specific Return Type (like int, double, or std::string) in the function signature, you physically force the function to give data back. The return keyword instantly ejects the data and completely terminates the function.
Syntax
// Function promises to return an 'int'
int multiply(int a, int b) {
int result = a * b;
return result; // Ejects the data!
}
int main() {
// The function call evaluates to the returned data
int mathData = multiply(5, 4);
std::cout << "Result: " << mathData << "\n"; // Prints 20
return 0;
}Common Pitfalls
- Forgetting the
returnstatement. If you declare a function asint calculate(), but forget to actually writereturn [value];inside it, C++ will return random garbage memory from the CPU register, completely corrupting your math. - Dead code after a return. The absolute moment the CPU hits a
returnstatement, the function immediately dies and exits. Any code written beneath areturnstatement is mathematically impossible to execute.
Interview Questions
Natively, no. A C++ function can only have one return type and can only return a single entity. However, you can bypass this limitation by returning a custom struct (which groups multiple variables together), using std::pair or std::tuple, or passing parameters by reference.
Real-World Example
Using early return statements as 'Guard Clauses' to instantly abort a function if invalid data is detected.
#include <iostream>
double divide(double a, double b) {
// GUARD CLAUSE: Protect against dividing by zero!
if (b == 0) {
std::cout << "Error: Division by zero!\n";
return 0.0; // Ejects immediately!
}
// This code only runs if 'b' is safe
return a / b;
}
int main() {
std::cout << divide(10, 0) << "\n";
std::cout << divide(10, 2) << "\n";
return 0;
}Check Your Knowledge
Test your understanding of Return Values with these quick questions.