C++ The return Keyword

Welcome to The Coding College! In this tutorial, we’ll discuss the return keyword in C++, its purpose, usage, and how it helps in controlling the flow of a program by returning values from functions.

What Is the return Keyword in C++?

The return keyword is used in a function to:

  1. Send a value back to the calling code.
  2. Terminate the function execution when encountered.

The type of the value returned must match the return type specified in the function declaration.

Syntax

return expression; // Sends a value back to the caller
return;            // Terminates the function (used in void functions)

Basic Example: Returning a Value

#include <iostream>
using namespace std;

// Function that returns an integer
int add(int a, int b) {
    return a + b; // Returns the sum
}

int main() {
    int result = add(5, 10); // Stores the returned value
    cout << "The sum is: " << result << endl;
    return 0;
}

Output:

The sum is: 15  

Returning from a void Function

If a function has a void return type, it doesn’t return a value but can use return; to terminate execution.

Example

#include <iostream>
using namespace std;

void greet(string name) {
    if (name.empty()) {
        cout << "Name cannot be empty!" << endl;
        return; // Ends the function early
    }
    cout << "Hello, " << name << "!" << endl;
}

int main() {
    greet("");          // Invalid input
    greet("Alice");     // Valid input
    return 0;
}

Output:

Name cannot be empty!  
Hello, Alice!  

Returning Multiple Values

C++ does not directly support returning multiple values, but you can achieve this by:

  1. Using structures or classes.
  2. Using pointers or references.
  3. Using std::tuple.

Example Using a Structure

#include <iostream>
using namespace std;

struct Result {
    int sum;
    int product;
};

Result calculate(int a, int b) {
    return {a + b, a * b}; // Return both sum and product
}

int main() {
    Result res = calculate(5, 10);
    cout << "Sum: " << res.sum << ", Product: " << res.product << endl;
    return 0;
}

Output:

Sum: 15, Product: 50  

Returning References

Functions can return references to variables, allowing direct modification of the original variable.

Example

#include <iostream>
using namespace std;

int& findMax(int &a, int &b) {
    return (a > b) ? a : b; // Returns reference to the larger variable
}

int main() {
    int x = 10, y = 20;
    findMax(x, y) = 50; // Modifies the larger value directly
    cout << "x: " << x << ", y: " << y << endl;
    return 0;
}

Output:

x: 10, y: 50  

Common Use Cases for return

1. Early Exit from Functions

void checkAge(int age) {
    if (age < 18) {
        cout << "Access denied!" << endl;
        return; // Ends the function
    }
    cout << "Access granted!" << endl;
}

2. Conditional Returns

bool isEven(int num) {
    return (num % 2 == 0); // Returns true if even, false otherwise
}

3. Chaining Function Calls

#include <iostream>
using namespace std;

int square(int x) {
    return x * x;
}

int main() {
    cout << "Square of 5: " << square(5) << endl;
    return 0;
}

Best Practices for Using return

  1. Match the Return Type: Ensure the value returned matches the function’s declared return type.
  2. Avoid Redundant Returns: Only include multiple return statements if they simplify code logic.
  3. Use return Consistently: Maintain a single exit point in complex functions when possible, for readability.
  4. Comment Complex Returns: Add comments for clarity if the returned value is computed or conditional.

Explore More on The Coding College

Understanding the return keyword is crucial for writing efficient and reusable functions. To explore advanced topics like lambda functions, recursion, and templates, visit The Coding College.

Leave a Comment