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

If the "something more semantic" is "iterator" then there is no reason not to use i; it is a well understood idiom.

查看更多
【Aperson】
3楼-- · 2020-02-11 18:54

my feeling is that the concept of using a single letter is fine for "simple" loops, however, i learned to use double-letters a long time ago and it has worked out great.

i asked a similar question last week and the following is part of my own answer:

// recommended style              ●    // "typical" single-letter style
                                  ●
for (ii=0; ii<10; ++ii) {         ●    for (i=0; i<10; ++i) {
    for (jj=0; jj<10; ++jj) {     ●        for (j=0; j<10; ++j) {
        mm[ii][jj] = ii * jj;     ●             m[i][j] = i * j;
    }                             ●        }
}                                 ●    }
in case the benefit isn't immediately obvious: searching through code for any single letter will find many things that aren't what you're looking for. the letter i occurs quite often in code where it isn't the variable you're looking for.

i've been doing it this way for at least 10 years.

note that plenty of people commented that either/both of the above are "ugly"...

查看更多
在下西门庆
4楼-- · 2020-02-11 18:55

I should point out that i and j are also mathematical notation for matrix indices. And usually, you're looping over an array. So it makes sense.

查看更多
登录 后发表回答