chtnnh
chtnnh

Reputation: 35

Does C support multiple assignment of the type a , b = 0, 1 like python does?

""" 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?

Upvotes: 3

Views: 1560

Answers (3)

Deduplicator
Deduplicator

Reputation: 45674

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

a, b = 0, 1;

The above is, considering operator precedence, equivalent to:

a, (b = 0), 1;

Which is equivalent to:

b = 0;

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

a = 0, b = 1;

That would be needlessly complex and confusing though, thus prefer separating it into two statements for much cleaner code:

a = 0;
b = 1;

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234785

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.

Upvotes: 1

dbush
dbush

Reputation: 224387

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

a = 0; b = 1;

Upvotes: 1

Related Questions