Coming Soon
This lesson is currently being developed
Function return values (value-returning functions)
Understand how functions can return values to the caller.
What to Expect
Comprehensive explanations with practical examples
Interactive coding exercises to practice concepts
Knowledge quiz to test your understanding
Step-by-step guidance for beginners
Development Status
Content is being carefully crafted to provide the best learning experience
Preview
Early Preview Content
This content is still being developed and may change before publication.
2.2 — Function return values (value-returning functions)
In this lesson, you'll learn about functions that return values, how to use return statements effectively, and best practices for value-returning functions.
What are value-returning functions?
A value-returning function is a function that computes a value and returns it to the caller. These functions have a return type other than void
and must include a return
statement that provides a value of that type.
return_type function_name(parameters)
{
// compute something
return value; // value must match return_type
}
The return statement
The return
statement serves two purposes:
- It immediately exits the function
- It sends a value back to the caller
#include <iostream>
int multiply(int x, int y)
{
int result = x * y;
return result; // Returns the computed value
// Any code after return is never executed
std::cout << "This will never print\n";
}
int main()
{
int answer = multiply(3, 4);
std::cout << "3 * 4 = " << answer << std::endl;
return 0;
}
Output:
3 * 4 = 12
Return types
Functions can return any valid C++ type:
Returning integers
int getAge()
{
return 25;
}
int calculateSum(int a, int b)
{
return a + b;
}
Returning floating-point numbers
double calculateCircleArea(double radius)
{
const double pi = 3.14159;
return pi * radius * radius;
}
double divideNumbers(double numerator, double denominator)
{
return numerator / denominator;
}
Returning characters
char getGrade(int score)
{
if (score >= 90)
return 'A';
else if (score >= 80)
return 'B';
else if (score >= 70)
return 'C';
else if (score >= 60)
return 'D';
else
return 'F';
}
Returning boolean values
bool isEven(int number)
{
return (number % 2 == 0);
}
bool isValidPassword(int length)
{
return length >= 8;
}
Using return values
You can use the return value in several ways:
1. Assign to a variable
#include <iostream>
double calculateTip(double bill, double tipPercent)
{
return bill * (tipPercent / 100.0);
}
int main()
{
double bill = 50.0;
double tip = calculateTip(bill, 15.0);
std::cout << "Bill: $" << bill << std::endl;
std::cout << "Tip: $" << tip << std::endl;
std::cout << "Total: $" << (bill + tip) << std::endl;
return 0;
}
2. Use directly in expressions
#include <iostream>
int square(int x)
{
return x * x;
}
int main()
{
// Use return value directly in calculations
int result = square(5) + square(3);
std::cout << "5² + 3² = " << result << std::endl;
// Use return value in conditions
if (square(4) > 10)
{
std::cout << "4² is greater than 10\n";
}
return 0;
}
Output:
5² + 3² = 34
4² is greater than 10
3. Chain function calls
#include <iostream>
double absolute(double x)
{
if (x < 0)
return -x;
else
return x;
}
double square(double x)
{
return x * x;
}
int main()
{
double value = -5.0;
// Chain function calls
double result = square(absolute(value));
std::cout << "square(absolute(" << value << ")) = " << result << std::endl;
return 0;
}
Output:
square(absolute(-5)) = 25
Multiple return statements
A function can have multiple return statements, but only one will execute:
#include <iostream>
int getMax(int a, int b)
{
if (a > b)
return a; // Returns immediately if a is larger
else
return b; // Returns immediately if b is larger or equal
}
std::string getTimeOfDay(int hour)
{
if (hour < 12)
return "Morning";
else if (hour < 17)
return "Afternoon";
else
return "Evening";
}
int main()
{
std::cout << "Max of 10 and 7: " << getMax(10, 7) << std::endl;
std::cout << "15:00 is " << getTimeOfDay(15) << std::endl;
return 0;
}
Output:
Max of 10 and 7: 10
15:00 is Afternoon
Early returns for efficiency
You can use return statements to exit a function early:
#include <iostream>
bool isPrime(int number)
{
// Handle special cases
if (number < 2)
return false; // Numbers less than 2 are not prime
if (number == 2)
return true; // 2 is the only even prime
if (number % 2 == 0)
return false; // Even numbers > 2 are not prime
// Check odd divisors up to sqrt(number)
for (int i = 3; i * i <= number; i += 2)
{
if (number % i == 0)
return false; // Found a divisor, not prime
}
return true; // No divisors found, number is prime
}
int main()
{
for (int i = 1; i <= 20; ++i)
{
if (isPrime(i))
std::cout << i << " is prime\n";
}
return 0;
}
Common mistakes and best practices
❌ Avoid: Missing return statement
int badFunction(int x)
{
if (x > 0)
return x;
// Missing return for x <= 0 case!
// This will cause undefined behavior
}
✅ Correct: All code paths return a value
int goodFunction(int x)
{
if (x > 0)
return x;
else
return 0; // Handle all cases
}
❌ Avoid: Unreachable code after return
int wastefulFunction(int x)
{
return x * 2;
// This code will never execute
std::cout << "This is unreachable!\n";
int unused = x + 1;
}
✅ Best practice: Meaningful return values
// Good: Clear what the function returns
double calculateInterest(double principal, double rate, int years)
{
return principal * rate * years / 100.0;
}
// Even better: Document with comments
/**
* Calculates simple interest
* @param principal The initial amount
* @param rate Annual interest rate (as percentage)
* @param years Number of years
* @return The total interest earned
*/
double calculateSimpleInterest(double principal, double rate, int years)
{
return principal * rate * years / 100.0;
}
Value categories and return types
When returning values, be mindful of the return type:
#include <iostream>
// Return by value (makes a copy)
int getValue()
{
int local = 42;
return local; // Safe: returns a copy of local
}
// Be careful with return type precision
double divideInts(int a, int b)
{
return static_cast<double>(a) / b; // Explicit conversion to avoid integer division
}
int main()
{
std::cout << "getValue() returns: " << getValue() << std::endl;
std::cout << "7 / 3 = " << divideInts(7, 3) << std::endl;
return 0;
}
Output:
getValue() returns: 42
7 / 3 = 2.33333
Summary
Value-returning functions are essential for creating modular, reusable code. Key points to remember:
- Use
return
statement to send a value back to the caller - The return type must match the type of the returned value
- Functions can have multiple return statements
- All code paths in a value-returning function should return a value
- Return statements immediately exit the function
- Use meaningful return types and consider precision requirements
Quiz
- What happens when a return statement is executed?
- Can a function have multiple return statements?
- What's wrong with this function?
int mystery(int x) { if (x > 0) return x; }
- How can you use a function's return value?
Practice exercises
Try implementing these functions:
double fahrenheitToCelsius(double fahrenheit)
- Converts temperaturebool isLeapYear(int year)
- Determines if a year is a leap yearint factorial(int n)
- Calculates factorial of a positive integerchar getLetterGrade(double percentage)
- Returns letter grade for percentage
Explore More Courses
Discover other available courses while this lesson is being prepared.
Browse CoursesLesson Discussion
Share your thoughts and questions