Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 498
george mano Avatar asked Jan 12 '12 10:01

george mano


People also ask

Can you assign multiple variables at once in C?

Example - Declaring multiple variables in a statement and assigning values. If your variables are the same type, you can define multiple variables in one declaration statement. You can also assign the variables a value in the declaration statement.

Can I assign 2 variables at once?

Multiple variable assignment is also known as tuple unpacking or iterable unpacking. It allows us to assign multiple variables at the same time in one single line of code. In the example above, we assigned three string values to three variables in one shot. As the output shows, the assignment works as we expect.

Can we assign multiple values to multiple variables at a time?

We can assign values to multiple variables at once in a single statement in Swift. We need to wrap the variables inside a bracket and assign the values using the equal sign = . The values are also wrapped inside a bracket.

Can we use 2 variables in for loop in C?

Yes, by using the comma operator. E.g. for (i=0, j=0; i<10; i++, j++) { ... }


2 Answers

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);
like image 139
filmor Avatar answered Sep 20 '22 13:09

filmor


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
like image 45
ezheng Avatar answered Sep 17 '22 13:09

ezheng