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?
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.
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.
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]
Try it out with those definitions:
int x; bool y; int z; x = y = z = 10;
And be surprised about the value of x.
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.
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