Which is the better way of declaring variables?
1.
int i,j,k;
2.
int i;
int j;
int k;
Can anybody explain which开发者_StackOverflow社区 is the better way and why?
This is ultimately a matter of personal taste. It doesn't matter to the compiler or your program either way.
If you're working on a team with other programmers, the important thing is that you follow their established standards. If you're maintaining a base of existing code, follow the style already established in the source. Otherwise, you're free to make your own decisions about how to format your code.
Personally, I prefer the second style. It makes it much clearer to me what the types are of each variable. Additionally, if you're working in C or C++ and declaring pointers, it's important to keep in mind that
int* i, j, k;
will only declare i
as a pointer to an int
(see this question for more discussion). Using the second declaration style makes it completely unambiguous, which is always better for long-term maintainability. The amount you're saving by squashing all variable declarations to one line doesn't seem worth it to me.
It's a matter of taste, there is no difference as far as the compiler is concerned
the first might help in readability and easy spotting of variables in declaration especially if you are not using any IDE and the code is long in single file
You need to define "better". When it comes to the program's efficiency, there's no difference.
If you're refering to styling, then I believe it's most readable and convenient to allow every variable a line for itself:
int i; // Holds the value of...
int j; // Iterator for...
int k; // Dummy for function()...
That also gives you the option for nice descriptive comments per each. Naturally, it boils down to your (and your team's as Cody stated) taste and conventions.
Depends on what level of readability, understandability and comprehensiveness you want to keep in your code. First type qualifies well in terms of understandability whereas second fits better in terms of readability and comprehensiveness.
Also as mentioned by @Code Gray, it can be confusing to use first syntax in some languages if it isn't used carefully.
Usually first type is always used in loops but in declaration sections, I prefer second one.
In the end, it is your choice and style that you want to adopt.
精彩评论