名为i的变量是不可接受的吗?

Vir*_*dia 17 variables iterator coding-style naming-conventions

就变量命名约定而言,是应该命名迭代器i还是更像语义的东西count?如果你不使用i,为什么不呢?如果您认为这i是可以接受的,是否存在不应该使用迭代的情况?

Jos*_*osh 35

取决于我想的背景.如果你在某个集合中循环遍历一组对象,那么从上下文中你应该做的事情应该是相当明显的.

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

但是,如果从上下文中不能立即清楚它正在做什么,或者如果要对索引进行修改,则应使用更能指示用法的变量名称.

for(int currentRow = 0; currentRow < numRows; currentRow++)
{
    for(int currentCol = 0; currentCol < numCols; currentCol++)
    {
        someTable[currentRow][currentCol] = someValue;
    }
} 
Run Code Online (Sandbox Code Playgroud)

  • currentRow和currentCol可以很容易地被称为row和col. (3认同)

And*_*ter 15

"i" 表示程序员的"循环计数器".这没什么不对.


Ian*_*n P 6

这是另一个完全没问题的例子:

foreach (Product p in ProductList)
{
    // Do something with p
}
Run Code Online (Sandbox Code Playgroud)

  • 绝对.没有人会抱怨读取"考虑连续函数f"的数学证明是不可理解的,因为函数被称为"f"而不是"a_continuous_function". (3认同)

pax*_*blo 5

我倾向于使用i,j,k进行非常局部化的循环(仅在源线数量方面存在很短的时间).对于存在于较大源区域的变量,我倾向于使用更详细的名称,因此我可以在不回溯代码的情况下查看它们的用途.

顺便说一下,我认为这些命名约定来自早期的Fortran语言,我是第一个整数变量(A - H是浮点数)?