RaviTej310
RaviTej310

Reputation: 1715

C++ simultaneous assignment of values to variables

I need to write a certain code segment in a c++ program that performs a task of the following type.

b:=a+b;
a:=a-b;

where := operator means that the value on the right hand side of all the expressions are computed first and then the variables on the left hand side of each expression is equated with the computed values on the right.

For example, in the above code, if a=5 and b=3, i would need the final value of a and b to be 8 and 2 respectively instead of 8 and -3 which i would get if i perform normal assignment.

Upvotes: 3

Views: 1126

Answers (2)

Barry
Barry

Reputation: 302862

You could use std::tie() and std::make_tuple():

std::tie(a, b) = std::make_tuple(a-b, a+b);

tie creates a tuple of references, and tuple assignment is equivalent to element-wise assignment. So this is effectively the same as:

// create the right-hand-side-tuple
auto __tmp1 = a-b;
auto __tmp2 = a+b;
// assign to the left-hand-side references
a = __tmp1;
b = __tmp2;

But since the assignment here is conceptually "atomic", you can write it all in one line - since all of the operations (the a-b and the a+b) are sequenced before the assignment itself.

Upvotes: 9

Logicrat
Logicrat

Reputation: 4468

You could use structures with names like before and after to hold your variables. Then, regardless of how many variables you have, you can use code as follows:

after.a = before.a + before.b;
after.b = before.a - before.b;

and then once your computations are done, you could move all the new values by the statement:

before = after;

Upvotes: 0

Related Questions