Let's assume we have declared integer variables a
and b
somewhere in the program. The following pieces of code behave identically.
1.
a = 1;
b = 1;
2.
a = b = 1;
However, is there any C++ code convention (Google C++ Style Guide didn't give me an answer) that tells us in which way to write?
Why would you need one? This is just a matter of individual style (most of the time, as there are situations in which I prefer to clearly distinguish between groups of commands related to different parts of the algorithm).
A convention is necessary in a situation where different choices can lead to different results (like some right hand rules in physics), but not here, IMO.
Interesting, I was pretty sure that multiple assignments are against the Google Style Guide (and was even mentioning this couple of times when reviewing someone's code), but indeed the style guide does not mention this at all.
I think this is not a matter of coding style. Those two pieces of code actually mean different things. The first one means: we have two variables which have no relation between them and coincidentally equal to 1 in the beginning. The second one: we have two variables that are equal to each other in the beginning and their value is 1.
So, to know which one is preferable we have to know what those a and b mean.
Actually, many people don't care about that. For example, unexperienced coders who think that it's not possible to assign the same value to several variables at once, so they use just the first one. Or, some people deliberately try to make the code shorter and use the second one all the time.
So while it's good to not keep it a matter of style, it still happens.
Being a Python beginner, I have once spent about half an hour debugging a solution which worked incorrectly because of a line like this one:
(I naively expected a and b to point to two different empty lists, while in reality, both pointed to the same list, of course).
Now, I prefer not to use such a construction, and this is one of the reasons. Also, most of the time, even if two variables are initialized with the same value, they are not related to each other, which makes the "a = b = 1" construction nonsemantic and just a really ugly way to make your program one line shorter.
There is popular idea — to avoid constructions which have side-effect. That is why python lacks pre/post inc/decrement operations. This construction has side effect — while assigning value of some expression to a we also change expression b.
However it is not extremely important problem, I think, so you can follow your personal tastes or if you are working in command — follow the style rules of this command. Usually you will have no problem switching between these two styles (especially if stylechecker is on).