19
int DFS(a, b,c,d)
{
    first=a+b;
    second=c+d;
    return(first,second);
}

solution, cost_limit = DFS(a, b,c,d);

can I do something like this ? and how?

Kemin Zhou
  • 6,264
  • 2
  • 48
  • 56
george mano
  • 5,948
  • 6
  • 33
  • 43
  • It's very unclear what you're asking here. I would suggest you explain what you mean by assign, and what you mean by a variable. – Samuel Harmer Jan 12 '12 at 10:55

5 Answers5

29

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);
filmor
  • 30,840
  • 6
  • 50
  • 48
12

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
ztyreg
  • 139
  • 2
  • 4
1

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);
    
eddi
  • 49,088
  • 6
  • 104
  • 155
Tudor
  • 61,523
  • 12
  • 102
  • 142
  • 3
    This is clearly not what the OP is asking for. He's asking for returning two separate values into two separate variables. – Szabolcs Jan 12 '12 at 10:32
  • 1
    This is not what he asked for. He wants the pythonic way, meaning `solution = first; cost_limit = second;` – filmor Jan 12 '12 at 10:33
0

One thing you should be know is that if a,b,c,d are not base types, but instances of a class you defined, let's say Foo, and you overload the = operator of the class, you must ensure the fact that the operator will return a reference to the object which is assigned, or else you will not be able to chain assignments ( solution = cost_limit = DFS(..) will only assign to cost_limit). The = operator should look like this:

Foo& Foo::operator =(const Foo& other)
    {
       //do stuff
       return other;
    }
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
0

If C++11 is not possible, it's possible to use references.

By passing a reference to variables in parameters.

int DFS(int a, int b, int c, int d, int &cost_limit)
{
    cost_limit = c + d;
    return a + b;
}

int solution, cost_limit;

solution = DFS(a, b, c, d, cost_limit);
BAK
  • 972
  • 8
  • 23