Can i assign in 2 variables at the same time in C++?

In C++11 you can use the tuple types and tie for that.

#include <tuple>

std::tuple<int, int> DFS (int a, int b, int c, int d)
{
    return std::make_tuple(a + b, c + d);
}

...

int solution, cost_limit;
std::tie(solution, cost_limit) = DFS(a, b, c, d);

You can do this two ways:

  1. Create a struct with two values and return it:

    struct result
    {
        int first;
        int second;
    };
    
    struct result DFS(a, b, c, d)
    {            
        // code
    }
    
  2. Have out parameters:

    void DFS(a, b, c, d, int& first, int& second)
    {
        // assigning first and second will be visible outside
    }
    

    call with:

    DFS(a, b, c, d, first, second);
    

With C++17, you can unpack a pair or a tuple

auto[i, j] = pair<int, int>{1, 2};
cout << i << j << endl; //prints 12
auto[l, m, n] = tuple<int, int, int>{1, 2, 3};
cout << l << m << n << endl; //prints 123

Tags:

C++