Structs

8.4 - Structured binding


Have you ever wondered on how to make your function return more than one value? You can return a struct to do that instead of using modifying multiple reference parameters.

For example, you want a function that does a division that returns both the integer quotient and the remainder. You can do so like this:

struct Values
{
    int quotient, remainder;
}

Values divide(int a, int b)
{
    return {a / b, a % b};
}

Then the caller can even use structured binding to make it look like a multiple value as well:

int main()
{
    auto [quotient, remainder] = divide(17, 5);

    std::cout << quotient << " " << remainder << std::endl;
}