Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel assignment in C++

Tags:

c++

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.

like image 269
Nick Avatar asked Nov 08 '08 20:11

Nick


People also ask

What is parallel assignment in programming?

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.

Is multiple assignment possible in C?

Since C language does not support chaining assignment like a=b=c; each assignment operator (=) operates on two operands only.

What is assignment in C programming?

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.

What is variable assignment in C?

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.


1 Answers

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.

like image 195
Johannes Schaub - litb Avatar answered Sep 30 '22 17:09

Johannes Schaub - litb