Language: EN

cpp-retorno-funciones

Return of Functions in C++

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

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 return one value directly. But we can return a grouping of several (for example, structures or classes).

Return of void

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;
}

Return of a value

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

Upon reaching a return statement, 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;
}

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;
}

Returning collections

Functions can also return collections like 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;
}

Using tuples

Starting from C++17, tuples can be used 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;
}

Practical examples