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

心不动则不痛 提交于 2020-01-03 08:08:35

问题


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?


回答1:


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.




回答2:


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.




回答3:


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]); 
  }
} 



回答4:


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.




回答5:


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]);
                }
              }
            }
          }
        }
      }
    }
  }
}



回答6:


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? (Hunt through the code to find that it's written ndx will bother me.)

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 non-player character, 'ai' to mean artificial intelligence, 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".)




回答7:


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.




回答8:


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.




回答9:


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.




回答10:


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
    }
}



回答11:


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.



来源:https://stackoverflow.com/questions/2886320/int-i-vs-int-index-etc-which-one-is-better

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!