cpp-retorno-funciones

Return of Functions in C++

  • 4 min

In C++, the return of a function is the mechanism by which a function can (optionally) return a value to the code that called it. This is done using the keyword return.

The returned value can be of any data type (primitive types, structs, objects…). It is also possible for a function not to return any value, which is indicated by the return type void.

In general, we can only directly return a single value. But we can return a grouping of several (for example, structures or classes).

If you want to learn more, check out the Introduction to Programming Course

Void Return

When a function does not need to return any value, it is declared with the return type void. In this case, the function performs an action without providing a result.

#include <iostream>

void Greet() {
    std::cout << "Hello!" << std::endl;
}

int main() {
    Greet(); // Prints "Hello!"
    return 0;
}
Copied!

Returning a Value

To return a value from a function, the reserved word return is used. The function’s return type must match the type of the returned value.

When a return statement is reached, the execution of the function stops and control is returned to the calling function.

#include <iostream>

int Add(int a, int b) {
    return a + b;
}

int main() {
    int result = Add(3, 4);
    std::cout << "The sum is: " << result << std::endl; // Prints "The sum is: 7"
    return 0;
}
Copied!

Returning Multiple Values

Although you cannot directly return more than one value from a function, there are several techniques to return multiple values in C++:

Using Classes or Structures

A common way is to encapsulate the values in a class or structure and return an instance of that class or structure.

#include <iostream>

struct Result {
    int number;
    std::string text;
};

Result GetResult() {
    return {42, "Example"};
}

int main() {
    Result res = GetResult();
    std::cout << "Number: " << res.number << ", Text: " << res.text << std::endl; // Prints "Number: 42, Text: Example"
    return 0;
}
Copied!

Returning Collections

Functions can also return collections such as arrays, vectors, lists, or maps.

#include <iostream>
#include <vector>

std::vector<int> GetList() {
    return {1, 2, 3, 4, 5};
}

int main() {
    std::vector<int> list = GetList();
    for (int num : list) {
        std::cout << num << " ";
    }
    std::cout << std::endl; // Prints "1 2 3 4 5"
    return 0;
}
Copied!

Using Tuples

Starting from C++17, you can use tuples to return multiple values. Tuples allow grouping values of different types into a single object.

#include <iostream>
#include <tuple>

std::tuple<int, std::string> GetData() {
    return {42, "Example"};
}

int main() {
    auto [number, text] = GetData();
    std::cout << "Number: " << number << ", Text: " << text << std::endl; // Prints "Number: 42, Text: Example"
    return 0;
}
Copied!

Practical Examples