views:

289

answers:

11

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?

+13  A: 

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.

Noon Silk
I don't know about the "and so on" bit. Going to four levels probably warrants a rethink of the design. Plus, `l` is a terrible name for a variable in any context (a kind of natural barrier :-).
Marcelo Cantos
@Marcelo: Of course. I actually start loops with `k` and proceed to `m` and `n`, I've never needed a fourth :P
Noon Silk
not if you matrixes are column major. In linear algebra world m and n are pretty much standard for dimensions, not to running variables (which are i,j,k)
aaa
+7  A: 

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.

unutbu
`i` is a standard index variable that should be recognizable in pretty much any loop structure.
Jason
+1  A: 

If it is small block, and there are no nested for loops, i is just fine, it's almost as unwritten rule that i is a loop incremental variable whenever it appears. In everything more complex, good naming is crucial.

mr.b
+2  A: 

When it comes to naming, it's all about clarity. I'd say most people who look at code know that "int i" is some sort of index, but they probably assume it's a plain old vanilla usage. So if it does something clever (ie not just simple counting up), you should call it something that makes this fact clear.

Carlos
+1  A: 

Personally I use i,j however instead of loop variables I tend to try and use for each when the language allows it - I find that even better.

Anders K.
Yes of course, but this is both relating to my coding in C and C# and possibly even a bit of Ruby
Earlz
+1 .. if indexes are not needed and the language supports collection iteration, I prefer it even if it's slower.
Anurag
+4  A: 

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]); 
  }
} 
jball
Do you mean like `row,column` ?
Earlz
pseudocode follows any convention you wish - switching it to a comma just because.
jball
what if you have three-dimensional array or three nested loops (matrix matrix multiply)? I think i,j,k is as descriptive as you can be
aaa
@aaa, it's true in some situations, but in most situations I think descriptive nested iterator names can be chosen.
jball
A: 

I never use single-letter variable names for one simple reason -- have you ever tried to search for all occurrences of a certain variable in a file, or across multiple files? It's better to use something a little less ambiguous and more searchable.

Ether
If your single-letter identifiers are always scoped tightly, then it's meaningless to search for all occurrences of them. :)
dash-tom-bang
+1  A: 

I frequently use x and y for instances when I am parsing some 2-dimensional object like a bitmap.

for (int (y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        // work
    }
}
JYelton
+2  A: 

I use single-letter variables as counters a lot. Here is how I loop, exhaustively use the letters in the alphabet:

for (int i = 0, l = array.length; i < l; i ++) {
  for (int j = 0, m = array[i].length; j < m; j ++) {
    for (int k = 0, n = array[i][j].length; k < n; k ++) {
      for (int o = 0, p = array[i][j][k].length; o < p; o ++) {
        for (int q = 0, r = array[i][j][k][o].length; q < r; q ++) {
          for (int s = 0, t = array[i][j][k][o][q].length; s < t; s ++) {
            for (int u = 0, v = array[i][j][k][o][q][s].length; u < v; u ++) {
              for (int w = 0, x = array[i][j][k][o][q][s][u].length; w < x; w ++) {
                for (int y = 0, z = array[i][j][k][o][q][s][u][w].length; y < z; y ++) {
                  f(array[i][j][k][o][q][s][u][w][y]);
                }
              }
            }
          }
        }
      }
    }
  }
}
SHiNKiROU
awesome +1.. now if that would've been `array[country][state][county][town][street][building][house][residents][0][name]`, I would've been stumped.
Anurag
oh my god the horror!
Earlz
Not to mention the fact that that l, m, n, p, r, t, v, and x suck as loop variables.
Anurag
looks like perl in a good shape.
mr.b
I worked on a piece of code where they used a,r,s,e as vars. It spelled out a[r][s] = e in the inner loop. Still not sure if that was on purpose.
sal
MY EYES OH GODMYEYESWHYARETHEYBURNING THE GOGGLES THEY DO NOTHING
Jason
+3  A: 

Short variable names are great, but they should have small scopes. And they should honor the conventions of the language. Until the day I day, my Haskell and ML code will have function-valued variables f, g, and h and monadic computations m, variables of unnknown type a and b, and lists of unknown element types as and bs. But the scopes of these variables will be limited to short functions or where clauses.

My C code will have variables called i, j, p, q, s, and t. But the scopes of these variables will be confined to individual loops (all praise C99 and the C++ backports!) or short functions. Whether it's a loop index or another variable, something that appears in a large scope gets a longer name.

Norman Ramsey
how come no `r` variable ?
aaa
+1  A: 

The scope of an item's visibility should dictate how descriptive that name needs to be.

If you literally have a tiny loop, i, j, and k are fine and typical index counters. Sometimes a more descriptive name can help illuminate intent, but if the for loop is set up like the following, then a more descriptive name doesn't really matter.

for (int i = 0; i < totalCount; ++i)
{
   Thing& myThing = things[i];

   // do stuff with myThing, never refer to i again
}

That said, abbreviations should never be used unless they're used consistently. I personally think ndx is a terrible identifier because it's hard to type; I can type English perfectly well and my programming speed is not limited by my typing speed. If you want to say index say index.

I believe that it was in The Pragmatic Programmer that they said you shouldn't use abbreviations because then people will never know what abbreviation to use. I know I want a thing called index so I type index but I get a compiler error. Now what?

As I try to think about it, about the only abbreviation that I use that isn't game specific is 'num' to stand in for 'numberOf'. Other than that I use 'npc' to mean player, etc., etc., and sometimes I use abbreviations in small blocks, e.g. a 10-line function operating on a Camera may just call it 'cam', but the scope is small so it's easy to see what's going on and the possibility for confusion is limited.

So- small scope -> do whatever you like (as long as there's some consistency). Large scope -> make your names unambiguous, meaningful, and easy to type. (By "easy to type" I mean "easy to remember how to spell" as well as "don't go overboard".)

dash-tom-bang