Given these alternatives:
int x, y, z;
or
int x;
int y;
int z;
Is there any real reason to choose one over the other?
|
Given these alternatives:
or
Is there any real reason to choose one over the other? |
|||
|
|
I'll be the outlier and take a firm stand on the subject. The second way is better. It's more readable, easier to maintain/refactor, and avoids potentially confusing statements like So if you're deciding on a set of standards to adopt as official code-style guidelines, always choose the second option. One declaration per line is better in nearly all cases. The exceptions to this are uncommon cases where you need 100 variables (and can't put them in a That said, if you're maintaining existing code, it's almost always best to just follow whatever conventions are already in use. Mixing two styles in the same source file does not often produce readable results. Readability and consistency are important, and unfortunately that means if someone has implemented code using sub-optimal coding style sometimes the best option is to just continue using that style. |
||||
|
|
|
Do it like specified in your code style guide. From my experience, there is no final argument for any version. I would prefer the second way to use a new line for every variable, because it is less error prone and could be more readable for more complex types and modifiers. But someone can easily disagree pointing to some code/language which forces you to use a lot of variables and to declare them at the beginning of the program/source. And to have 200 lines, each for one variable, is not so nice. |
|||||||||||||||
|
|
I'd put the variable declarations to separate lines. From Code Complete, 2nd Edition, p759:
|
|||||
|
|
I don't believe one way is better than the other. I would prefer the latter if the types differ at all though. |
||||
|
|
|
Generally, there is no difference between these two ways. I prefer second way because of better readability, although, it happens sometimes to use first one (when having short names variables used as counters, or in some other similar way). In practice, it depends on your own preferences or, if you are working in a team, it's best if all members of the team are using same way of declaration. |
|||
|
|
|
I don't think there's a clear advantage of one approach over the other. There might be an argument for the first approach if x, y and z are closely related and the second if not, but it's not a strong argument. |
|||
|
|