Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are multiple assignments in one line considered bad style? [closed]

Tags:

In C++ you can do multiple assignment by doing this

x = y = z = 10; 

Yet multiple people have told me that is a bad style and I shouldn't be using it without giving me a reason why.

Can someone please explain to me why this is considered a bad style?

like image 985
Caesar Avatar asked Dec 31 '12 21:12

Caesar


People also ask

What is the purpose of multiple assignments?

Multiple assignment (also known as tuple unpacking or iterable unpacking) allows you to assign multiple variables at the same time in one line of code.

Is multiple assignment possible in C?

MultipleAssignment is a language property of being able to assign one value to more than one variables. It usually looks like the following: a = b = c = d = 0 // assigns all variables to 0.

What is a double assignment?

In highly-object-oriented languages, double assignment results in the same object being assigned to multiple variables, so changes in one variable are reflected in the other. $ python -c 'a = b = [] ; a.append(1) ; print b' [1]


2 Answers

Try it out with those definitions:

int x; bool y; int z; x = y = z = 10; 

And be surprised about the value of x.

like image 133
Sjoerd Avatar answered Sep 19 '22 18:09

Sjoerd


It's not inherently bad style, but you can often make the code clearer by doing just one assignment per line and letting the compiler optimizer sort things out. If you use the multiple-assignment style then sometimes it might not be clear whether x = y = z = 10; was intentional or whether it was a typo for something like x = y = z + 10;. By always limiting yourself to one assignment per statement you make it obvious when typos occur.

like image 22
Mark B Avatar answered Sep 19 '22 18:09

Mark B