Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings)
#include <iostream>
int main() {
int a = 4;
int b = 5;
a, b = b, a;
std::cout << "a: " << a << endl
<< "b: " << b << endl;
return 0;
}
and prints:
a: 4
b: 5
What I'd like it to print ... if it weren't obvious, is:
a: 5
b: 4
As in, say, ruby, or python.
Finally, parallel assignment is any assignment expression that has more than one lvalue or more than one rvalue. Here is a simple example: x,y,z = 1,2,3 # Set x to 1, y to 2 and z to 3.
Since C language does not support chaining assignment like a=b=c; each assignment operator (=) operates on two operands only.
An assignment operation assigns the value of the right-hand operand to the storage location named by the left-hand operand. Therefore, the left-hand operand of an assignment operation must be a modifiable l-value. After the assignment, an assignment expression has the value of the left operand but is not an l-value.
Assigning values to C and C++ variables Assignment expressions assign a value to the left operand. The left operand must be a modifiable lvalue. An lvalue is an expression representing a data object that can be examined and altered. C contains two types of assignment operators: simple and compound.
That's not possible. Your code example
a, b = b, a;
is interpreted in the following way:
a, (b = b), a
It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens.
The proper way doing this is just
std::swap(a, b);
Boost includes a tuple class with which you can do
tie(a, b) = make_tuple(b, a);
It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With