User-Defined Functions with Return Values
Functions with return values are one of the most commonly used types of functions in C++ programming. These functions perform calculations or operations and return a result to the caller. Understanding how to write and use functions with return values is crucial for mastering C++ programming.
Basic Syntax Structure
ReturnType FunctionName(ParameterList) {
// Function body
return Expression; // Return a value that matches the declared type
}
Basic Example: Weight Conversion Function
Let’s start with an example from the textbook and analyze the various components of a function with a return value:
#include <iostream>
using namespace std;
// Function prototype - Declare the existence and format of the function
int stonetolb(int); // Accepts an int parameter and returns an int value
int main() {
int stone;
cout << "Enter the weight in stone: ";
cin >> stone;
// Function call - Assign the return value to a variable
int pounds = stonetolb(stone);
cout << stone << " stone = ";
cout << pounds << " pounds." << endl;
return 0;
}
// Function definition - Implement the specific conversion logic
int stonetolb(int sts) {
return 14 * sts; // Return the calculated result
}
Detailed Analysis of the Elements of Functions with Return Values
1. Importance of Return Type
#include <iostream>
using namespace std;
// Examples of different return types
// Return integer
int getAge() {
return 25;
}
// Return double
double calculateArea(double radius) {
return 3.14159 * radius * radius;
}
// Return boolean
bool isAdult(int age) {
return age >= 18;
}
// Return character
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';
}
// Return string
string getGreeting(string name) {
return "Hello, " + name + "!";
}
int main() {
cout << "Age: " << getAge() << endl;
cout << "Area of circle with radius 3: " << calculateArea(3.0) << endl;
cout << "Is 18 an adult: " << isAdult(18) << endl;
cout << "Grade for score 85: " << getGrade(85) << endl;
cout << getGreeting("Zhang San") << endl;
return 0;
}
2. Various Forms of the return Statement
#include <iostream>
using namespace std;
// 1. Directly return the result of an expression (most common form)
int square(int x) {
return x * x; // Return the result of the expression
}
// 2. Return a variable value
int getMax(int a, int b) {
int maxValue;
if (a > b) {
maxValue = a;
} else {
maxValue = b;
}
return maxValue; // Return the value of the variable
}
// 3. Conditional return
string checkTemperature(double temp) {
if (temp > 30.0) {
return "Hot";
} else if (temp > 20.0) {
return "Warm";
} else if (temp > 10.0) {
return "Cool";
} else {
return "Cold";
}
}
// 4. Early return
bool isValidNumber(int num) {
if (num < 0) {
return false; // Early return
}
if (num > 100) {
return false; // Early return
}
return true; // Final return
}
// 5. Return complex expressions
double calculateCompoundInterest(double principal, double rate, int years) {
return principal * pow(1 + rate / 100, years);
}
int main() {
cout << "Square of 5: " << square(5) << endl;
cout << "Max of 10 and 20: " << getMax(10, 20) << endl;
cout << "Weather at 25 degrees: " << checkTemperature(25.0) << endl;
cout << "Is 50 valid: " << isValidNumber(50) << endl;
cout << "Compound interest result: " << calculateCompoundInterest(1000, 5, 3) << endl;
return 0;
}
Practical Example Extensions
Example 1: Mathematical Calculation Toolkit
#include <iostream>
#include <cmath>
using namespace std;
// Function prototype declarations
double calculateBMI(double weight, double height);
double celsiusToFahrenheit(double celsius);
double fahrenheitToCelsius(double fahrenheit);
double calculateDistance(double x1, double y1, double x2, double y2);
bool isPrime(int number);
int main() {
// Test various calculation functions
// BMI calculation
double weight = 70.5; // kg
double height = 1.75; // m
double bmi = calculateBMI(weight, height);
cout << "Weight " << weight << "kg, Height " << height << "m BMI: " << bmi << endl;
// Temperature conversion
double celsius = 25.0;
double fahrenheit = celsiusToFahrenheit(celsius);
cout << celsius << "°C = " << fahrenheit << "°F" << endl;
cout << fahrenheit << "°F = " << fahrenheitToCelsius(fahrenheit) << "°C" << endl;
// Distance calculation
double distance = calculateDistance(0, 0, 3, 4);
cout << "Distance from point (0,0) to point (3,4): " << distance << endl;
// Prime number check
int testNumber = 17;
cout << testNumber << (isPrime(testNumber) ? " is prime" : " is not prime") << endl;
return 0;
}
// Function definitions
// Calculate Body Mass Index (BMI)
double calculateBMI(double weight, double height) {
return weight / (height * height);
}
// Celsius to Fahrenheit
double celsiusToFahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32.0;
}
// Fahrenheit to Celsius
double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32.0) * 5.0 / 9.0;
}
// Calculate distance between two points
double calculateDistance(double x1, double y1, double x2, double y2) {
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
// Check for prime number
bool isPrime(int number) {
if (number <= 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
for (int i = 3; i * i <= number; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
Example 2: Geometric Shape Calculations
#include <iostream>
#include <cmath>
using namespace std;
// Function prototypes
double circleArea(double radius);
double circleCircumference(double radius);
double rectangleArea(double length, double width);
double rectanglePerimeter(double length, double width);
double triangleArea(double base, double height);
double trianglePerimeter(double side1, double side2, double side3);
int main() {
// Circle calculations
double radius = 5.0;
cout << "Circle - Radius: " << radius << endl;
cout << "Area: " << circleArea(radius) << endl;
cout << "Circumference: " << circleCircumference(radius) << endl;
cout << endl;
// Rectangle calculations
double length = 8.0, width = 6.0;
cout << "Rectangle - Length: " << length << ", Width: " << width << endl;
cout << "Area: " << rectangleArea(length, width) << endl;
cout << "Perimeter: " << rectanglePerimeter(length, width) << endl;
cout << endl;
// Triangle calculations
double base = 10.0, height = 5.0;
double side1 = 3.0, side2 = 4.0, side3 = 5.0;
cout << "Triangle - Base: " << base << ", Height: " << height << endl;
cout << "Area: " << triangleArea(base, height) << endl;
cout << "Perimeter of sides " << side1 << ", " << side2 << ", " << side3 << ": "
<< trianglePerimeter(side1, side2, side3) << endl;
return 0;
}
// Function definitions
// Circle area
double circleArea(double radius) {
return M_PI * radius * radius;
}
// Circle circumference
double circleCircumference(double radius) {
return 2 * M_PI * radius;
}
// Rectangle area
double rectangleArea(double length, double width) {
return length * width;
}
// Rectangle perimeter
double rectanglePerimeter(double length, double width) {
return 2 * (length + width);
}
// Triangle area
double triangleArea(double base, double height) {
return 0.5 * base * height;
}
// Triangle perimeter
double trianglePerimeter(double side1, double side2, double side3) {
return side1 + side2 + side3;
}
Example 3: Utility Functions
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// Function prototypes
string reverseString(string str);
int countVowels(string str);
string toUpperCase(string str);
string toLowerCase(string str);
bool isPalindrome(string str);
int findMax(int arr[], int size);
int main() {
// String operation tests
string testString = "Hello, World!";
cout << "Original string: " << testString << endl;
cout << "Reversed string: " << reverseString(testString) << endl;
cout << "Number of vowels: " << countVowels(testString) << endl;
cout << "Uppercase: " << toUpperCase(testString) << endl;
cout << "Lowercase: " << toLowerCase(testString) << endl;
string palindromeTest = "racecar";
cout << "\"" << palindromeTest << "\" "
<< (isPalindrome(palindromeTest) ? "is" : "is not") << " a palindrome" << endl;
// Array operation tests
int numbers[] = {3, 7, 2, 9, 1, 8, 4};
int size = sizeof(numbers) / sizeof(numbers[0]);
cout << "Max value in array: " << findMax(numbers, size) << endl;
return 0;
}
// Function definitions
// Reverse string
string reverseString(string str) {
string reversed = str;
int n = reversed.length();
for (int i = 0; i < n / 2; i++) {
swap(reversed[i], reversed[n - i - 1]);
}
return reversed;
}
// Count vowels
int countVowels(string str) {
int count = 0;
string vowels = "aeiouAEIOU";
for (char c : str) {
if (vowels.find(c) != string::npos) {
count++;
}
}
return count;
}
// Convert to uppercase
string toUpperCase(string str) {
string result = str;
for (char &c : result) {
c = toupper(c);
}
return result;
}
// Convert to lowercase
string toLowerCase(string str) {
string result = str;
for (char &c : result) {
c = tolower(c);
}
return result;
}
// Check palindrome
bool isPalindrome(string str) {
string cleaned;
// Remove non-alphanumeric characters and convert to lowercase
for (char c : str) {
if (isalnum(c)) {
cleaned += tolower(c);
}
}
int left = 0, right = cleaned.length() - 1;
while (left < right) {
if (cleaned[left] != cleaned[right]) {
return false;
}
left++;
right--;
}
return true;
}
// Find max value in array
int findMax(int arr[], int size) {
int maxVal = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
Key Points Summary
-
Return type must match: The return type in the function declaration must be consistent with the type of the value returned by the return statement.
-
Function of the return statement:
- Ends function execution
- Returns control to the caller
- Returns a value to the caller
Expression evaluation: The expression following return will be evaluated, and the result will be the return value.
Various ways to call functions:
int result = stonetolb(15); // Assign to variable
cout << stonetolb(10) << endl; // Directly used for output
int total = stonetolb(5) + 10; // Used in expression
Design principles:
- Each function should accomplish a single, clear task
- Function names should clearly describe the function’s purpose
- Choose parameters and return types wisely
Compile and Run
# Compile the program
g++ -o return_functions return_functions.cpp
# Run the program
./return_functions
By mastering functions with return values, you can create more modular, reusable, and maintainable code. This is one of the foundational skills for building complex C++ applications.