Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int i vs int index etc. Which one is better? [duplicate]

Possible Duplicates:
Is a variable named i unacceptable?
What is an ideal variable naming convention for loop variables?

Coming from a C background I've always used int i for generic loop variables. Of course in big nested loops or other complex things I may use a descriptive name but which one had you rather see?

int i;
for(i=0;i<Controls.Count;i++){
  DoStuff(Controls[i]);
}

or

int index;
for(index=0;index<Controls.Count;index++){
  DoStuff(Controls[index]);
}

In the current project I am working on there are both of these styles and index being replaced by ndx.

Which one is better? Is the i variable too generic? Also what about the other C style names? i, j, k Should all of these be replaced by actual descriptive variables?

like image 930
Earlz Avatar asked May 21 '10 23:05

Earlz


3 Answers

i, however, is pretty standard in terms of the first loop, followed by j for an inner loop and k for an inner-inner loop, and so on.

As with almost all naming rules, as long as it is standard within a project, and works well for all members thereof, then it's fine.

like image 147
2 revs, 2 users 89% Avatar answered Nov 02 '22 19:11

2 revs, 2 users 89%


When possible, I'd favor descriptive names, since we should be striving for readable code.

For temporary variables that are used in a tight code block, a short variable name is acceptable.

But if the loop or code block is very long, it is better to have a longer descriptive variable name, if for no other reason than it will make doing text searches for it easier.

like image 8
unutbu Avatar answered Nov 02 '22 21:11

unutbu


If you are doing nested loops to access multi-dimensional array elements, descriptive iterator names are a must to create self-commenting code. eg.,

for(int i=0;i<someMax;i++){ 
  for(int j=0;j<someOtherMax;j++){ 
    DoStuff(someArray[i,j]); 
  }
} 

vs.

for(int row=0;row<someMax;row++){ 
  for(int column=0;column<someOtherMax;column++){ 
    DoStuff(someArray[row,column]); 
  }
} 
like image 5
2 revs Avatar answered Nov 02 '22 19:11

2 revs