Is a variable named i unacceptable? [closed]

2020-02-11 17:54发布

As far as variable naming conventions go, should iterators be named i or something more semantic like count? If you don't use i, why not? If you feel that i is acceptable, are there cases of iteration where it shouldn't be used?

21条回答
闹够了就滚
2楼-- · 2020-02-11 18:28

Depends on the context I suppose. If you where looping through a set of Objects in some collection then it should be fairly obvious from the context what you are doing.

for(int i = 0; i < 10; i++)
{
    // i is well known here to be the index
    objectCollection[i].SomeProperty = someValue;
}

However if it is not immediately clear from the context what it is you are doing, or if you are making modifications to the index you should use a variable name that is more indicative of the usage.

for(int currentRow = 0; currentRow < numRows; currentRow++)
{
    for(int currentCol = 0; currentCol < numCols; currentCol++)
    {
        someTable[currentRow][currentCol] = someValue;
    }
} 
查看更多
Lonely孤独者°
3楼-- · 2020-02-11 18:30

i is so common that it is acceptable, even for people that love descriptive variable names.

What is absolutely unacceptable (and a sin in my book) is using i,j, or k in any other context than as an integer index in a loop.... e.g.

foreach(Input i in inputs)
{
    Process(i);

}
查看更多
萌系小妹纸
4楼-- · 2020-02-11 18:30

The use of i, j, k for INTEGER loop counters goes back to the early days of FORTRAN.
Personally I don't have a problem with them so long as they are INTEGER counts.
But then I grew up on FORTRAN!

查看更多
女痞
5楼-- · 2020-02-11 18:31

i is definitely acceptable. Not sure what kind of justification I need to make -- but I do use it all of the time, and other very respected programmers do as well.

Social validation, I guess :)

查看更多
▲ chillily
6楼-- · 2020-02-11 18:34

Here's another example of something that's perfectly okay:

foreach (Product p in ProductList)
{
    // Do something with p
}
查看更多
看我几分像从前
7楼-- · 2020-02-11 18:40

As long as you're using it temporarily inside a simple loop and it's obvious what you're doing, sure. That said, is there no other short word you can use instead?

i is widely known as a loop iterator, so you're actually more likely to confuse maintenance programmers if you use it outside of a loop, but if you use something more descriptive (like filecounter), it makes code nicer.

查看更多
登录 后发表回答