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:46

Yes, in fact it's preferred since any programmer reading your code will understand that it's simply an iterator.

查看更多
小情绪 Triste *
3楼-- · 2020-02-11 18:47

It depends. If you're iterating over some particular set of data then I think it makes more sense to use a descriptive name. (eg. filecounter as Dan suggested).

However, if you're performing an arbitrary loop then i is acceptable. As one work mate described it to me - i is a convention that means "this variable is only ever modified by the for loop construct. If that's not true, don't use i"

查看更多
爷、活的狠高调
4楼-- · 2020-02-11 18:48

It helps if you name it something that describes what it is looping through. But I usually just use i.

查看更多
疯言疯语
5楼-- · 2020-02-11 18:48

I am going to go against the grain and say no.

For the crowd that says "i is understood as an iterator", that may be true, but to me that is the equivalent of comments like 'Assign the value 5 to variable Y. Variable names like comment should explain the why/what not the how.

To use an example from a previous answer:

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

Is it that much harder to just use a meaningful name like so?

for(int objectCollectionIndex = 0; objectCollectionIndex  < 10; objectCollectionIndex ++)
{
    objectCollection[objectCollectionIndex].SomeProperty = someValue;
}

Granted the (borrowed) variable name objectCollection is pretty badly named too.

查看更多
Evening l夕情丶
6楼-- · 2020-02-11 18:50

i is fine, but something like this is not:

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        string s = datarow[i][j].ToString(); // or worse
    }
}

Very common for programmers to inadvertently swap the i and the j in the code, especially if they have bad eyesight or their Windows theme is "hotdog". This is always a "code smell" for me - it's kind of rare when this doesn't get screwed up.

查看更多
神经病院院长
7楼-- · 2020-02-11 18:53

"i" means "loop counter" to a programmer. There's nothing wrong with it.

查看更多
登录 后发表回答