2
""" Sample python code representing multiple assignment """
a , b = 0 , 1
print a , b

The following code gives output : 0 1 and obviously does not raise any error. Does C support the same?

chtnnh
  • 25
  • 1
  • 8
  • 2
    No. The closest it comes is [this](https://stackoverflow.com/questions/19353686/multiple-assignment-in-one-line). – meowgoesthedog Sep 04 '18 at 14:59
  • Often when a language does not support a feature of interest, it means that the language has other ways to approach the higher level problem. What is the need to do multiple assignments? – chux - Reinstate Monica Sep 04 '18 at 15:31
  • @chux I needed to interchange the values of 3 variables inside the body of my for loop – chtnnh Sep 04 '18 at 15:36
  • You can do something like this: `void AssignValues(int values[], ... );` which would let you implement the first line like this: `int vals[]={0,1};AssignValues(vals, a, b);` but implementing it would be.... nasty. – Tim Randall Sep 04 '18 at 18:35

3 Answers3

1

No C does not support multiple assignments like this.

Compilation passes since a , b = 0 , 1 is grouped as a, (b = 0), 1. a and 1 are no-ops but still valid expressions; the expression is equivalent to

b = 0

with a not changed.

Interestingly, you can achieve your desired notation in C++ with some contrivance and a minor change in the syntax.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

C does not support list assignments as Python does. You need to assign to each variable separately:

a = 0; b = 1;
dbush
  • 205,898
  • 23
  • 218
  • 273
1

No, C does not support multiple-assignment, nor has it language-level support for tuples.

a, b = 0, 1;

The above is, considering to operator precedence, equivalent to:

a, (b = 0), 1;

Which is equivalent to:

b = 0;

See live on coliru.


The closest C-equivalent to your Python code would be:

a = 0, b = 1;

In this case, using the value of an assignment-expression isn't useful.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118