If you are writing a simple little loop, what should you name the counter?
如果您正在编写一个简单的小循环,您应该如何命名计数器?
Provide example loops!
提供示例循环!
28 个解决方案
#1
35
I always use a meaningful name unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use i
.
我总是使用有意义的名称,除非它是一个单层循环,而变量除了“通过这个循环的次数”之外没有其他含义,在这种情况下,我使用I。
When using meaningful names:
当使用有意义的名称:
- the code is more understandable to colleagues reading your code,
- 同事们读你的代码时,代码更容易理解,
- it's easier to find bugs in the loop logic, and
- 在循环逻辑中更容易找到bug。
- text searches for the variable name to return relevant pieces of code operating on the same data are more reliable.
- 对变量名进行文本搜索,以返回在相同数据上操作的相关代码片段更可靠。
Example - spot the bug
It can be tricky to find the bug in this nested loop using single letters:
要在这个嵌套循环中使用单个字母来发现错误是很困难的:
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int i, j, total;
total = 0;
for (i = 0; i < MAX_COLS; i++)
for (j = 0; j < MAX_ROWS; j++)
total += values[i][j];
return total;
}
whereas it is easier when using meaningful names:
而使用有意义的名字则比较容易:
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int row_num, col_num, total;
total = 0;
for (row_num = 0; row_num < MAX_COLS; row_num++)
for (col_num = 0; col_num < MAX_ROWS; col_num++)
total += values[row_num][col_num];
return total;
}
Why row_num
? - rejected alternatives
In response to some other answers and comments, these are some alternative suggestions to using row_num
and col_num
and why I choose not to use them:
对于其他一些答案和注释,这些是使用row_num和col_num的一些替代建议,以及为什么我选择不使用它们:
-
r
andc
: This is slightly better thani
andj
. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code. - r和c:这比i和j稍微好一点,如果我的组织的标准是单字母变量是整数,并且始终是等效描述性名称的第一个字母,我只考虑使用它们。如果我在函数中有两个变量,其名称以“r”开头,那么系统就会崩溃,即使在代码中出现“r”的其他对象出现时,可读性也会受到影响。
-
rr
andcc
: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better thanr
andc
. - rr和cc:这对我来说很奇怪,但我不习惯双字母循环变量的风格。如果它是我所在机构的标准,那么我想它会比r和c稍好一点。
-
row
andcol
: At first glance this seems more succinct thanrow_num
andcol_num
, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. Ifrow
could mean either the row structure itself, or a row number, then confusion will result. - row和col:乍一看,这似乎比row_num和col_num更简洁,而且更像描述。但是,我希望像“行”和“列”这样的空名词是指这些东西的结构、对象或指针。如果行可以表示行结构本身,或者行号,那么就会产生混淆。
-
iRow
andiCol
: This conveys extra information, sincei
can mean it's a loop counter whileRow
andCol
tell you what it's counting. However, I prefer to be able to read the code almost in English:-
row_num < MAX_COLS
reads as "the row number is less than the maximum (number of) columns"; - row_num < MAX_COLS读取“行号小于最大(数量)列”;
-
iRow < MAX_COLS
at best reads as "the integer loop counter for the row is less than the maximum (number of) columns". - iRow < MAX_COLS最好读为“行的整数循环计数器小于最大(数量)列”。
- It may be a personal thing but I prefer the first reading.
- 这可能是个人问题,但我更喜欢第一次阅读。
-
- iRow和iCol:这传达了额外的信息,因为我可以表示它是一个循环计数器,而Row和Col告诉你它在计算什么。但是,我更喜欢用英语阅读代码:row_num < MAX_COLS读取的是“行号小于最大(数量)列”;iRow < MAX_COLS最好读为“行的整数循环计数器小于最大(数量)列”。这可能是个人问题,但我更喜欢第一次阅读。
An alternative to row_num
I would accept is row_idx
: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.
row_num的另一种选择是row_idx:“index”一词唯一地表示数组位置,除非应用程序的域是数据库引擎设计、金融市场或类似的。
My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs.
我上面的例子是尽可能小的,因为这样一些人可能不知道变量的名称,因为他们可以把整个函数放在他们的脑子里。然而,在实际代码中,函数会更大,逻辑也更复杂,因此,合适的名称对于帮助可读性和避免bug变得更加重要。
In summary, my aim with all variable naming (not just loops) is to be completely unambiguous. If anybody reads any portion of my code and can't work out what a variable is for immediately, then I have failed.
总之,我的目标是所有变量命名(不只是循环)是完全明确的。如果有人读了我的代码的任何部分,并且不能确定一个变量是什么,那么我就失败了。
#2
35
1) For normal old style small loops - i, j, k - If you need more than 3 level nested loops, this means that either the algorithm is very specific and complex, either you should consider refactoring the code.
1)对于普通的旧式小循环- i, j, k -如果你需要超过3层的嵌套循环,这意味着要么这个算法是非常具体和复杂的,要么你应该考虑重构代码。
Java Example:
Java示例:
for(int i = 0; i < ElementsList.size(); i++) {
Element element = ElementsList.get(i);
someProcessing(element);
....
}
2) For the new style java loops like for(Element element: ElementsList)
it is better to use normal meanigful name
对于像For(元素元素:element)这样的新样式java循环,最好使用普通的有意义的名称。
Java Example:
Java示例:
for(Element element: ElementsList) {
someProcessing(element);
....
}
3) If it is possible with the language you use, convert the loop to use iterator
3)如果您使用的语言是可能的,那么将循环转换为使用迭代器。
Java Iterator Example: click here
Java迭代器示例:单击这里。
#3
12
Examples: . . . In Java
Non-Iterative Loops:
Non-Nested Loops: . . . The Index is a value.
非嵌套循环:…索引是一个值。
. . . using
i
, as you would in Algebra, is the most common practise . . .。使用i,就像你在代数中所做的那样,是最常见的练习。
for (int i = 0; i < LOOP_LENGTH; i++) {
// LOOP_BODY
}
Nested Loops: . . . Differentiating Indices lends to comprehension.
嵌套循环:…区分指数有助于理解。
. . . using a descriptive suffix . . .
。使用描述性后缀…
for (int iRow = 0; iRow < ROWS; iRow++) {
for (int iColumn = 0; iColumn < COLUMNS; iColumn++) {
// LOOP_BODY
}
}
foreach
Loops: . . . An Object
needs a name.
foreach循环:…对象需要名称。
. . . using a descriptive name . . .
。使用描述性名称…
for (Object something : somethings) {
// LOOP_BODY
}
Iterative Loops:
for
Loops: . . . Iterators reference Objects. An Iterator it is neither; an Index, nor an Indice.
for循环:…迭代器对象的引用。迭代器不是;一个索引,一个标记。
. . .
iter
abreviates an Iterators purpose . . .。iter abreviates一个迭代器的目的…
for (Iterator iter = collection.iterator(); iter.hasNext(); /* N/A */) {
Object object = iter.next();
// LOOP_BODY
}
while
Loops: . . . Limit the scope of the Iterator.
while循环:…限制迭代器的范围。
. . . commenting on the loops purpose . . .
。评论循环的目的…
/* LOOP_DESCRIPTION */ {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
// LOOP_BODY
}
}
This last example reads badly without comments, thereby encouraging them. It's verbose perhaps, but useful in scope limiting loops in C.
最后一个例子没有注释就很糟糕,因此鼓励了它们。它可能是冗长的,但是在C的范围限制循环中很有用。
#4
8
Always try to name the variable something meaningful and in context.
总是试着把变量命名为有意义的和上下文的。
If you cannot decide, then use "index", if only so that someone else (maybe you!) can more easily click on it for refactoring later.
如果您不能决定,那么使用“索引”,如果只是让其他人(可能是您!)可以更容易地单击它进行重构。
Paul Stephenson See this answer for an example.
保罗·斯蒂芬森以一个例子来回答这个问题。
#5
8
My experience is that most people use single letters, e.g.: i
, j
, k
, ... or x
, y
, or r
, c
(for row/column) or w
, h
(for width/height) , etc.
我的经验是,大多数人都使用单字母,例如:i, j, k,…或x, y,或r, c(行/列)或w, h(宽度/高度)等。
But I learned a great alternative a long time ago, and have used it ever since: double letter variables.
但是很久以前我就学会了一个很棒的选择,从那时起就开始使用它:双字母变量。
// 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.
如果这个好处不是显而易见的:在代码中搜索任何一个字母会发现很多不是你想要的东西。我在代码中经常出现的字母不是你要找的变量。
#6
6
I use i, j, k (or r & c for row-column looping). If you need more than three loop variables in a method, the the method is probably too long and complex and your code would likely benefit from splitting the method up into more methods and naming them properly.
我用I、j、k(或r & c表示行列循环)。如果在方法中需要三个以上的循环变量,那么这个方法可能太长、太复杂,您的代码可能会受益于将方法拆分为更多的方法并正确命名它们。
#7
5
i
我
if I have a nested loop then also j
.
如果我有一个嵌套循环,那么也有j。
This convention is so common that if you manage to come across a variable i
in a block of code that you can't see the start of you still instantly recognise it for what it is.
这个约定非常常见,如果您在代码块中遇到一个变量i,您就无法看到它的开始,您仍然可以立即识别它是什么。
#8
5
I use i, ii, iii, iv, v ... Never got higher than iii, though.
我用I, ii, iii, iv, v…不过,从来没有超过三岁。
#9
4
I use single letters only when the loop counter is an index. I like the thinking behind the double letter, but it makes the code quite unreadable.
只有当循环计数器是索引时,我才使用单个字母。我喜欢双字母后面的想法,但它让代码变得难以读懂。
#10
3
If the counter is to be used as an index to a container, I use i
, j
, k
.
如果计数器被用作一个容器的索引,我使用I, j, k。
If it is to be used to iterate over a range (or perform a set number of iterations), I often use n
. Though, if nesting is required I'll usually revert to i
, j
, k
.
如果要在一个范围上迭代(或者执行一个集合的迭代次数),我经常使用n.但是,如果需要嵌套,我通常会回到I, j, k。
In languages which provide a foreach
-style construct, I usually write like this:
在提供foreach风格构造的语言中,我通常这样写:
foreach widget in widgets do
foo(widget)
end
I think some people will tell me off for naming widget
so similarly to widgets
, but I find it quite readable.
我认为有些人会告诉我,对于小部件的命名和小部件一样,但是我觉得它很容易读懂。
#11
2
Like a previous poster, I also use ii, jj,.. mainly because in many fonts a single i looks very similar to 1.
像以前的海报一样,我也用了ii, jj。主要是因为在很多字体中,我看起来很像1。
#12
2
Steve McConnell's Code Complete has, as usual, some excellent advice in this regard. The relevant pages (in the first edition anyway) are 340 and 341. Definitely advise anyone who's interested in improving their loop coding to give this a look. McConnell recommends meaningful loop counter names but people should read what he's got to say themselves rather than relying on my weak summary.
像往常一样,史蒂夫·麦康奈尔的代码在这方面有一些很好的建议。相关的页数(在第一版中)是340和341。绝对建议任何有兴趣改进循环编码的人来看看。McConnell建议有意义的循环计数器名称,但人们应该阅读他必须说的内容,而不是依赖于我的弱摘要。
#13
1
I use "counter" or "loop" as the variable name. Modern IDEs usually do the word completion , so longer variable names are not as tedious to use. Besides , to name the variable to its functionality makes it clear to the programmer who is going to maintain your code as to what your intentions were.
我使用“counter”或“loop”作为变量名。现代的ide通常会完成单词的完成,所以使用更长的变量名并不是那么乏味。此外,将变量命名为它的功能使程序员能够清楚地知道您的意图是什么。
#14
1
Perl standard
In Perl, the standard variable name for an inner loop is $_. The for, foreach, and while statements default to this variable, so you don't need to declare it. Usually, $_ may be read like the neuter generic pronoun "it". So a fairly standard loop might look like:
在Perl中,内部循环的标准变量名是$_。for, foreach,和while语句默认为这个变量,所以您不需要声明它。通常,$_可以像中性的代名词“it”一样读。一个相当标准的循环可能是这样的:
foreach (@item){
$item_count{$_}++;
}
In English, that translates to:
在英语中,翻译为:
For each item, increment it's item_count.
对于每个项目,增加它的item_count。
Even more common, however, is to not use a variable at all. Many Perl functions and operators default to $_:
然而,更常见的是根本不使用变量。许多Perl函数和操作符默认为$_:
for (@item){
print;
}
In English:
英文:
For [each] item, print [it].
对于[每个]项,打印[它]。
This also is the standard for counters. (But counters are used far less often in Perl than in other languages such as C). So to print the squares of integers from 1 to 100:
这也是计数器的标准。(但在Perl中,计数器的使用要比其他语言(如C)少得多),因此,要将整数的平方从1打印到100:
for (1..100){
print "$_*$_\n";
}
Since only one loop can use the $_ variable, usually it's used in the inner-most loop. This usage matches the way English usually works:
因为只有一个循环可以使用$_变量,通常它在内部循环中使用。这种用法与英语通常的用法一致:
For each car, look at each tire and check it's pressure.
对于每一辆车,检查每个轮胎并检查它的压力。
In Perl:
在Perl中:
foreach $car (@cars){
for (@{$car->{tires}}){
check_pressure($_);
}
}
As above, it's best to use longer, descriptive names in outer loops, since it can be hard to remember in a long block of code what a generic loop variable name really means.
如上所述,最好在外部循环中使用更长的、描述性的名称,因为在长代码块中很难记住通用循环变量名称的真正含义。
Occasionally, it makes sense to use shorter, non-descriptive, generic names such as $i, $j, and $k, rather than $_ or a descriptive name. For instance, it's useful to match the variables use in a published algorithm, such as cross product.
偶尔,使用更短的、非描述性的、通用的名称,比如$i、$j和$k,而不是$_或描述性名称,这是有意义的。例如,在已发布的算法中,例如跨产品,匹配变量的使用是很有用的。
#15
1
The first rule is that the length of the variable name should match the scope of the variable. The second rule is that meaningful names make bugs more shallow. The third rule is that if you feel like adding comment to a variable name, you chose the wrong variable name. The final rule is do as your teammates do, so long as it does not counteract the prior rules.
第一个规则是变量名的长度应该与变量的范围相匹配。第二条规则是,有意义的名字会使错误变得更浅。第三条规则是,如果您想对变量名添加注释,则选择错误的变量名。最后的规则是像你的队友那样做,只要它不抵消之前的规则。
#16
1
@JustMike . . . A FEW C EXAMPLES: . . . to accompany the Java ones.
@JustMike。举几个C的例子:……伴随Java语言。
NON-NESTED loop: . . . limiting scope where possible
非嵌套循环:…限制在可能的范围
/*LOOP_DESCRIPTION*/ {
int i;
for (i = 0; i < LOOP_LENGTH; i++) {
// loop body
}
}
NESTED loop: . . . ditto
嵌套循环:…同上
/*LOOP_DESCRIPTION*/ {
int row, column;
for (row = 0; row < ROWS; row++) {
for (column = 0; column < COLUMNS; column++) {
// loop body
}
}
}
One good thing about this layout is it reads badly without comments, thereby encouraging them.
It's verbose perhaps, but personally this is how I do loops in C.
Also: I did use "index" and "idx" when I started, but this usually got changed to "i" by my peers.
这种布局的优点之一是,如果没有注释,它会读得很糟糕,从而鼓励它们。也许有点啰嗦,但就我个人而言,这就是我在c中循环的方式:我在开始时确实使用了“索引”和“idx”,但这通常会被我的同事改为“I”。
#17
1
Whatever you choose, use the same index consistently in your code wherever it has the same meaning. For example, to walk through an array, you can use i
, jj
, kappa
, whatever, but always do it the same way everywhere:
无论您选择什么,都要在代码中始终如一地使用相同的索引。例如,你可以使用i, jj, kappa,无论什么,但总是这样做:
for (i = 0; i < count; i++) ...
The best practice is to make this part of the loop look the same throughout your code (including consistently using count
as the limit), so that it becomes an idiom that you can skip over mentally in order to focus on the meat of the code, the body of the loop.
最佳实践是使循环的这一部分看起来相同的在你的代码(包括持续使用数作为限制),这样它就成了一个成语,你可以跳过精神为了专注于代码的肉,身体的循环。
Similarly, if you're walking through an 2d array of pixels, for example, you might write
类似地,如果您正在遍历一个二维的像素数组,例如,您可能会编写。
for (y = 0; y < height; y++)
for (x = 0; x < width; x++)
...
Just do it the same way in every place that you write this type of loop.
在写这种循环的每个地方都用同样的方法。
You want your readers to be able to ignore the boring setup and see the brilliance of what you're doing in the actual loop.
您希望您的读者能够忽略那些乏味的设置,并看到您在实际循环中所做的事情的卓越性。
#18
1
I have long used the i/j/k naming scheme. But recently I've started to adapt a more consequent naming method.
我一直使用I /j/k命名方案。但最近,我开始采用一种更顺势的命名方法。
I allready named all my variables by its meaning, so why not name the loop variable in the same deterministic way.
我已经根据它的含义命名了所有变量,所以为什么不以相同的确定性方法命名循环变量。
As requested a few examples:
请举几个例子:
If you need to loop trough a item collection.
如果您需要循环槽的一个项目集合。
for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)
{
...
}
But i try to avoid the normal for loops, because I tend to want the real item in the list and use that, not the actual position in the list. so instead of beginning the for block with a:
但是我试图避免循环的正常,因为我倾向于想要列表中的实项,而不是列表中的实际位置。所以不要用a来表示block
Item currentItem = list[currentItemIndex];
I try to use the foreach construct of the language. which transforms the.
我试着使用每种语言的构造。这改变了。
for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)
{
Item currentItem = list[currentItemIndex];
...
}
into
成
foreach (Item currentItem in list)
{
...
}
Which makes it easier to read because only the real meaning of the code is expressed (process the items in the list) and not the way we want to process the items (keep an index of the current item en increase it until it reaches the length of the list and thereby meaning the end of the item collection).
这使得它更容易阅读,因为只有代码的真正意义表达(过程中的商品列表)并不是我们想要的方式处理项目(保持索引的当前项增加,直到它到达列表的长度,从而意味着结束的项目集合)。
The only time I still use one letter variables is when I'm looping trough dimensions. But then I will use x, y and sometimes z.
我唯一一次使用一个字母的变量是当我循环槽的尺寸。然后我用x, y,有时z。
#19
1
i also use the double-letter convention. ii, jj, kk. you can grep those and not come up with a bunch of unwanted matches.
我还使用了双字母惯例。二世,jj,kk。你可以把那些不需要的比赛加到一起。
i think using those letters, even though they're doubled, is the best way to go. it's a familiar convention, even with the doubling.
我认为使用这些字母是最好的方法。这是一个熟悉的习惯,即使是加倍。
there's a lot to say for sticking with conventions. it makes things a lot more readable.
对于遵守惯例有很多要说的。它让事情变得更有可读性。
#20
0
I've started using perlisms in php.
我已经开始在php中使用perlisms。
if its a singular iteration, $_
is a good name for those who know its use.
如果它是一个单一的迭代,$_对于知道它使用的人来说是一个好名字。
#21
0
My habit is to use 't' - close to 'r' so it follows easily aftewr typing 'for'
我的习惯是使用“t”-接近“r”,所以它很容易就可以输入“for”
#22
0
If it is a simple counter, I stick to using 'i' otherwise, have name that denotes the context. I tend to keep the variable length to 4. This is mainly from code reading point of view, writing is doesn't count as we have auto complete feature.
如果它是一个简单的计数器,我就会使用“I”,否则,就有表示上下文的名称。我倾向于将变量长度保持为4。这主要是从代码阅读的角度来看,写作是不算数的,因为我们有自动完成的功能。
#23
0
I've started to use context-relevant loop variable names mixed with hungarian.
我已经开始使用上下文相关的循环变量名和匈牙利语混合。
When looping through rows, I'll use iRow
. When looping through columns I'll use iCol
. When looping through cars I'll use iCar
. You get the idea.
当循环通过行时,我将使用iRow。当循环通过列时,我将使用iCol。当你在车里盘旋的时候,我会用iCar。你懂的。
#24
0
for numerical computations, matlab, and the likes of it, dont use i, j
对于数值计算,matlab,等等,不用i, j。
these are reserved constants, but matlab wont complain.
这些是保留的常量,但matlab不会抱怨。
My personal favs are
我个人的比如是
index first,second counter count
指数第一,第二计数器计数
#25
0
My favorite convention for looping over a matrix-like set is to use x+y as they are used in cartesian coordinates:
我最喜欢用x+y作为矩阵的循环,因为它们在笛卡尔坐标系中使用:
for x in width:
for y in height:
do_something_interesting(x,y)
#26
0
I usually use:
我通常使用:
for(lcObject = 0; lcObject < Collection.length(); lcObject++)
{
//do stuff
}
#27
0
For integers I use int index, unless it's nested then I use an Index suffix over what's being iterated like int groupIndex and int userIndex.
对于整数,我使用int索引,除非它是嵌套的,然后我使用一个索引后缀来遍历像int groupIndex和int userIndex这样的迭代。
#28
0
In Python, I use i, j, and k if I'm only counting times through. I use x, y, and z if the iteration count is being used as an index. If I'm actually generating a series of arguments, however, I'll use a meaningful name.
在Python中,我使用I、j和k,如果我只是计算时间。如果迭代计数被用作索引,我将使用x、y和z。如果我实际上生成了一系列的参数,我将使用一个有意义的名称。
#1
35
I always use a meaningful name unless it's a single-level loop and the variable has no meaning other than "the number of times I've been through this loop", in which case I use i
.
我总是使用有意义的名称,除非它是一个单层循环,而变量除了“通过这个循环的次数”之外没有其他含义,在这种情况下,我使用I。
When using meaningful names:
当使用有意义的名称:
- the code is more understandable to colleagues reading your code,
- 同事们读你的代码时,代码更容易理解,
- it's easier to find bugs in the loop logic, and
- 在循环逻辑中更容易找到bug。
- text searches for the variable name to return relevant pieces of code operating on the same data are more reliable.
- 对变量名进行文本搜索,以返回在相同数据上操作的相关代码片段更可靠。
Example - spot the bug
It can be tricky to find the bug in this nested loop using single letters:
要在这个嵌套循环中使用单个字母来发现错误是很困难的:
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int i, j, total;
total = 0;
for (i = 0; i < MAX_COLS; i++)
for (j = 0; j < MAX_ROWS; j++)
total += values[i][j];
return total;
}
whereas it is easier when using meaningful names:
而使用有意义的名字则比较容易:
int values[MAX_ROWS][MAX_COLS];
int sum_of_all_values()
{
int row_num, col_num, total;
total = 0;
for (row_num = 0; row_num < MAX_COLS; row_num++)
for (col_num = 0; col_num < MAX_ROWS; col_num++)
total += values[row_num][col_num];
return total;
}
Why row_num
? - rejected alternatives
In response to some other answers and comments, these are some alternative suggestions to using row_num
and col_num
and why I choose not to use them:
对于其他一些答案和注释,这些是使用row_num和col_num的一些替代建议,以及为什么我选择不使用它们:
-
r
andc
: This is slightly better thani
andj
. I would only consider using them if my organisation's standard were for single-letter variables to be integers, and also always to be the first letter of the equivalent descriptive name. The system would fall down if I had two variables in the function whose name began with "r", and readability would suffer even if other objects beginning with "r" appeared anywhere in the code. - r和c:这比i和j稍微好一点,如果我的组织的标准是单字母变量是整数,并且始终是等效描述性名称的第一个字母,我只考虑使用它们。如果我在函数中有两个变量,其名称以“r”开头,那么系统就会崩溃,即使在代码中出现“r”的其他对象出现时,可读性也会受到影响。
-
rr
andcc
: This looks weird to me, but I'm not used to a double-letter loop variable style. If it were the standard in my organisation then I imagine it would be slightly better thanr
andc
. - rr和cc:这对我来说很奇怪,但我不习惯双字母循环变量的风格。如果它是我所在机构的标准,那么我想它会比r和c稍好一点。
-
row
andcol
: At first glance this seems more succinct thanrow_num
andcol_num
, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. Ifrow
could mean either the row structure itself, or a row number, then confusion will result. - row和col:乍一看,这似乎比row_num和col_num更简洁,而且更像描述。但是,我希望像“行”和“列”这样的空名词是指这些东西的结构、对象或指针。如果行可以表示行结构本身,或者行号,那么就会产生混淆。
-
iRow
andiCol
: This conveys extra information, sincei
can mean it's a loop counter whileRow
andCol
tell you what it's counting. However, I prefer to be able to read the code almost in English:-
row_num < MAX_COLS
reads as "the row number is less than the maximum (number of) columns"; - row_num < MAX_COLS读取“行号小于最大(数量)列”;
-
iRow < MAX_COLS
at best reads as "the integer loop counter for the row is less than the maximum (number of) columns". - iRow < MAX_COLS最好读为“行的整数循环计数器小于最大(数量)列”。
- It may be a personal thing but I prefer the first reading.
- 这可能是个人问题,但我更喜欢第一次阅读。
-
- iRow和iCol:这传达了额外的信息,因为我可以表示它是一个循环计数器,而Row和Col告诉你它在计算什么。但是,我更喜欢用英语阅读代码:row_num < MAX_COLS读取的是“行号小于最大(数量)列”;iRow < MAX_COLS最好读为“行的整数循环计数器小于最大(数量)列”。这可能是个人问题,但我更喜欢第一次阅读。
An alternative to row_num
I would accept is row_idx
: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.
row_num的另一种选择是row_idx:“index”一词唯一地表示数组位置,除非应用程序的域是数据库引擎设计、金融市场或类似的。
My example above is as small as I could make it, and as such some people might not see the point in naming the variables descriptively since they can hold the whole function in their head in one go. In real code, however, the functions would be larger, and the logic more complex, so decent names become more important to aid readability and to avoid bugs.
我上面的例子是尽可能小的,因为这样一些人可能不知道变量的名称,因为他们可以把整个函数放在他们的脑子里。然而,在实际代码中,函数会更大,逻辑也更复杂,因此,合适的名称对于帮助可读性和避免bug变得更加重要。
In summary, my aim with all variable naming (not just loops) is to be completely unambiguous. If anybody reads any portion of my code and can't work out what a variable is for immediately, then I have failed.
总之,我的目标是所有变量命名(不只是循环)是完全明确的。如果有人读了我的代码的任何部分,并且不能确定一个变量是什么,那么我就失败了。
#2
35
1) For normal old style small loops - i, j, k - If you need more than 3 level nested loops, this means that either the algorithm is very specific and complex, either you should consider refactoring the code.
1)对于普通的旧式小循环- i, j, k -如果你需要超过3层的嵌套循环,这意味着要么这个算法是非常具体和复杂的,要么你应该考虑重构代码。
Java Example:
Java示例:
for(int i = 0; i < ElementsList.size(); i++) {
Element element = ElementsList.get(i);
someProcessing(element);
....
}
2) For the new style java loops like for(Element element: ElementsList)
it is better to use normal meanigful name
对于像For(元素元素:element)这样的新样式java循环,最好使用普通的有意义的名称。
Java Example:
Java示例:
for(Element element: ElementsList) {
someProcessing(element);
....
}
3) If it is possible with the language you use, convert the loop to use iterator
3)如果您使用的语言是可能的,那么将循环转换为使用迭代器。
Java Iterator Example: click here
Java迭代器示例:单击这里。
#3
12
Examples: . . . In Java
Non-Iterative Loops:
Non-Nested Loops: . . . The Index is a value.
非嵌套循环:…索引是一个值。
. . . using
i
, as you would in Algebra, is the most common practise . . .。使用i,就像你在代数中所做的那样,是最常见的练习。
for (int i = 0; i < LOOP_LENGTH; i++) {
// LOOP_BODY
}
Nested Loops: . . . Differentiating Indices lends to comprehension.
嵌套循环:…区分指数有助于理解。
. . . using a descriptive suffix . . .
。使用描述性后缀…
for (int iRow = 0; iRow < ROWS; iRow++) {
for (int iColumn = 0; iColumn < COLUMNS; iColumn++) {
// LOOP_BODY
}
}
foreach
Loops: . . . An Object
needs a name.
foreach循环:…对象需要名称。
. . . using a descriptive name . . .
。使用描述性名称…
for (Object something : somethings) {
// LOOP_BODY
}
Iterative Loops:
for
Loops: . . . Iterators reference Objects. An Iterator it is neither; an Index, nor an Indice.
for循环:…迭代器对象的引用。迭代器不是;一个索引,一个标记。
. . .
iter
abreviates an Iterators purpose . . .。iter abreviates一个迭代器的目的…
for (Iterator iter = collection.iterator(); iter.hasNext(); /* N/A */) {
Object object = iter.next();
// LOOP_BODY
}
while
Loops: . . . Limit the scope of the Iterator.
while循环:…限制迭代器的范围。
. . . commenting on the loops purpose . . .
。评论循环的目的…
/* LOOP_DESCRIPTION */ {
Iterator iter = collection.iterator();
while (iter.hasNext()) {
// LOOP_BODY
}
}
This last example reads badly without comments, thereby encouraging them. It's verbose perhaps, but useful in scope limiting loops in C.
最后一个例子没有注释就很糟糕,因此鼓励了它们。它可能是冗长的,但是在C的范围限制循环中很有用。
#4
8
Always try to name the variable something meaningful and in context.
总是试着把变量命名为有意义的和上下文的。
If you cannot decide, then use "index", if only so that someone else (maybe you!) can more easily click on it for refactoring later.
如果您不能决定,那么使用“索引”,如果只是让其他人(可能是您!)可以更容易地单击它进行重构。
Paul Stephenson See this answer for an example.
保罗·斯蒂芬森以一个例子来回答这个问题。
#5
8
My experience is that most people use single letters, e.g.: i
, j
, k
, ... or x
, y
, or r
, c
(for row/column) or w
, h
(for width/height) , etc.
我的经验是,大多数人都使用单字母,例如:i, j, k,…或x, y,或r, c(行/列)或w, h(宽度/高度)等。
But I learned a great alternative a long time ago, and have used it ever since: double letter variables.
但是很久以前我就学会了一个很棒的选择,从那时起就开始使用它:双字母变量。
// 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.
如果这个好处不是显而易见的:在代码中搜索任何一个字母会发现很多不是你想要的东西。我在代码中经常出现的字母不是你要找的变量。
#6
6
I use i, j, k (or r & c for row-column looping). If you need more than three loop variables in a method, the the method is probably too long and complex and your code would likely benefit from splitting the method up into more methods and naming them properly.
我用I、j、k(或r & c表示行列循环)。如果在方法中需要三个以上的循环变量,那么这个方法可能太长、太复杂,您的代码可能会受益于将方法拆分为更多的方法并正确命名它们。
#7
5
i
我
if I have a nested loop then also j
.
如果我有一个嵌套循环,那么也有j。
This convention is so common that if you manage to come across a variable i
in a block of code that you can't see the start of you still instantly recognise it for what it is.
这个约定非常常见,如果您在代码块中遇到一个变量i,您就无法看到它的开始,您仍然可以立即识别它是什么。
#8
5
I use i, ii, iii, iv, v ... Never got higher than iii, though.
我用I, ii, iii, iv, v…不过,从来没有超过三岁。
#9
4
I use single letters only when the loop counter is an index. I like the thinking behind the double letter, but it makes the code quite unreadable.
只有当循环计数器是索引时,我才使用单个字母。我喜欢双字母后面的想法,但它让代码变得难以读懂。
#10
3
If the counter is to be used as an index to a container, I use i
, j
, k
.
如果计数器被用作一个容器的索引,我使用I, j, k。
If it is to be used to iterate over a range (or perform a set number of iterations), I often use n
. Though, if nesting is required I'll usually revert to i
, j
, k
.
如果要在一个范围上迭代(或者执行一个集合的迭代次数),我经常使用n.但是,如果需要嵌套,我通常会回到I, j, k。
In languages which provide a foreach
-style construct, I usually write like this:
在提供foreach风格构造的语言中,我通常这样写:
foreach widget in widgets do
foo(widget)
end
I think some people will tell me off for naming widget
so similarly to widgets
, but I find it quite readable.
我认为有些人会告诉我,对于小部件的命名和小部件一样,但是我觉得它很容易读懂。
#11
2
Like a previous poster, I also use ii, jj,.. mainly because in many fonts a single i looks very similar to 1.
像以前的海报一样,我也用了ii, jj。主要是因为在很多字体中,我看起来很像1。
#12
2
Steve McConnell's Code Complete has, as usual, some excellent advice in this regard. The relevant pages (in the first edition anyway) are 340 and 341. Definitely advise anyone who's interested in improving their loop coding to give this a look. McConnell recommends meaningful loop counter names but people should read what he's got to say themselves rather than relying on my weak summary.
像往常一样,史蒂夫·麦康奈尔的代码在这方面有一些很好的建议。相关的页数(在第一版中)是340和341。绝对建议任何有兴趣改进循环编码的人来看看。McConnell建议有意义的循环计数器名称,但人们应该阅读他必须说的内容,而不是依赖于我的弱摘要。
#13
1
I use "counter" or "loop" as the variable name. Modern IDEs usually do the word completion , so longer variable names are not as tedious to use. Besides , to name the variable to its functionality makes it clear to the programmer who is going to maintain your code as to what your intentions were.
我使用“counter”或“loop”作为变量名。现代的ide通常会完成单词的完成,所以使用更长的变量名并不是那么乏味。此外,将变量命名为它的功能使程序员能够清楚地知道您的意图是什么。
#14
1
Perl standard
In Perl, the standard variable name for an inner loop is $_. The for, foreach, and while statements default to this variable, so you don't need to declare it. Usually, $_ may be read like the neuter generic pronoun "it". So a fairly standard loop might look like:
在Perl中,内部循环的标准变量名是$_。for, foreach,和while语句默认为这个变量,所以您不需要声明它。通常,$_可以像中性的代名词“it”一样读。一个相当标准的循环可能是这样的:
foreach (@item){
$item_count{$_}++;
}
In English, that translates to:
在英语中,翻译为:
For each item, increment it's item_count.
对于每个项目,增加它的item_count。
Even more common, however, is to not use a variable at all. Many Perl functions and operators default to $_:
然而,更常见的是根本不使用变量。许多Perl函数和操作符默认为$_:
for (@item){
print;
}
In English:
英文:
For [each] item, print [it].
对于[每个]项,打印[它]。
This also is the standard for counters. (But counters are used far less often in Perl than in other languages such as C). So to print the squares of integers from 1 to 100:
这也是计数器的标准。(但在Perl中,计数器的使用要比其他语言(如C)少得多),因此,要将整数的平方从1打印到100:
for (1..100){
print "$_*$_\n";
}
Since only one loop can use the $_ variable, usually it's used in the inner-most loop. This usage matches the way English usually works:
因为只有一个循环可以使用$_变量,通常它在内部循环中使用。这种用法与英语通常的用法一致:
For each car, look at each tire and check it's pressure.
对于每一辆车,检查每个轮胎并检查它的压力。
In Perl:
在Perl中:
foreach $car (@cars){
for (@{$car->{tires}}){
check_pressure($_);
}
}
As above, it's best to use longer, descriptive names in outer loops, since it can be hard to remember in a long block of code what a generic loop variable name really means.
如上所述,最好在外部循环中使用更长的、描述性的名称,因为在长代码块中很难记住通用循环变量名称的真正含义。
Occasionally, it makes sense to use shorter, non-descriptive, generic names such as $i, $j, and $k, rather than $_ or a descriptive name. For instance, it's useful to match the variables use in a published algorithm, such as cross product.
偶尔,使用更短的、非描述性的、通用的名称,比如$i、$j和$k,而不是$_或描述性名称,这是有意义的。例如,在已发布的算法中,例如跨产品,匹配变量的使用是很有用的。
#15
1
The first rule is that the length of the variable name should match the scope of the variable. The second rule is that meaningful names make bugs more shallow. The third rule is that if you feel like adding comment to a variable name, you chose the wrong variable name. The final rule is do as your teammates do, so long as it does not counteract the prior rules.
第一个规则是变量名的长度应该与变量的范围相匹配。第二条规则是,有意义的名字会使错误变得更浅。第三条规则是,如果您想对变量名添加注释,则选择错误的变量名。最后的规则是像你的队友那样做,只要它不抵消之前的规则。
#16
1
@JustMike . . . A FEW C EXAMPLES: . . . to accompany the Java ones.
@JustMike。举几个C的例子:……伴随Java语言。
NON-NESTED loop: . . . limiting scope where possible
非嵌套循环:…限制在可能的范围
/*LOOP_DESCRIPTION*/ {
int i;
for (i = 0; i < LOOP_LENGTH; i++) {
// loop body
}
}
NESTED loop: . . . ditto
嵌套循环:…同上
/*LOOP_DESCRIPTION*/ {
int row, column;
for (row = 0; row < ROWS; row++) {
for (column = 0; column < COLUMNS; column++) {
// loop body
}
}
}
One good thing about this layout is it reads badly without comments, thereby encouraging them.
It's verbose perhaps, but personally this is how I do loops in C.
Also: I did use "index" and "idx" when I started, but this usually got changed to "i" by my peers.
这种布局的优点之一是,如果没有注释,它会读得很糟糕,从而鼓励它们。也许有点啰嗦,但就我个人而言,这就是我在c中循环的方式:我在开始时确实使用了“索引”和“idx”,但这通常会被我的同事改为“I”。
#17
1
Whatever you choose, use the same index consistently in your code wherever it has the same meaning. For example, to walk through an array, you can use i
, jj
, kappa
, whatever, but always do it the same way everywhere:
无论您选择什么,都要在代码中始终如一地使用相同的索引。例如,你可以使用i, jj, kappa,无论什么,但总是这样做:
for (i = 0; i < count; i++) ...
The best practice is to make this part of the loop look the same throughout your code (including consistently using count
as the limit), so that it becomes an idiom that you can skip over mentally in order to focus on the meat of the code, the body of the loop.
最佳实践是使循环的这一部分看起来相同的在你的代码(包括持续使用数作为限制),这样它就成了一个成语,你可以跳过精神为了专注于代码的肉,身体的循环。
Similarly, if you're walking through an 2d array of pixels, for example, you might write
类似地,如果您正在遍历一个二维的像素数组,例如,您可能会编写。
for (y = 0; y < height; y++)
for (x = 0; x < width; x++)
...
Just do it the same way in every place that you write this type of loop.
在写这种循环的每个地方都用同样的方法。
You want your readers to be able to ignore the boring setup and see the brilliance of what you're doing in the actual loop.
您希望您的读者能够忽略那些乏味的设置,并看到您在实际循环中所做的事情的卓越性。
#18
1
I have long used the i/j/k naming scheme. But recently I've started to adapt a more consequent naming method.
我一直使用I /j/k命名方案。但最近,我开始采用一种更顺势的命名方法。
I allready named all my variables by its meaning, so why not name the loop variable in the same deterministic way.
我已经根据它的含义命名了所有变量,所以为什么不以相同的确定性方法命名循环变量。
As requested a few examples:
请举几个例子:
If you need to loop trough a item collection.
如果您需要循环槽的一个项目集合。
for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)
{
...
}
But i try to avoid the normal for loops, because I tend to want the real item in the list and use that, not the actual position in the list. so instead of beginning the for block with a:
但是我试图避免循环的正常,因为我倾向于想要列表中的实项,而不是列表中的实际位置。所以不要用a来表示block
Item currentItem = list[currentItemIndex];
I try to use the foreach construct of the language. which transforms the.
我试着使用每种语言的构造。这改变了。
for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)
{
Item currentItem = list[currentItemIndex];
...
}
into
成
foreach (Item currentItem in list)
{
...
}
Which makes it easier to read because only the real meaning of the code is expressed (process the items in the list) and not the way we want to process the items (keep an index of the current item en increase it until it reaches the length of the list and thereby meaning the end of the item collection).
这使得它更容易阅读,因为只有代码的真正意义表达(过程中的商品列表)并不是我们想要的方式处理项目(保持索引的当前项增加,直到它到达列表的长度,从而意味着结束的项目集合)。
The only time I still use one letter variables is when I'm looping trough dimensions. But then I will use x, y and sometimes z.
我唯一一次使用一个字母的变量是当我循环槽的尺寸。然后我用x, y,有时z。
#19
1
i also use the double-letter convention. ii, jj, kk. you can grep those and not come up with a bunch of unwanted matches.
我还使用了双字母惯例。二世,jj,kk。你可以把那些不需要的比赛加到一起。
i think using those letters, even though they're doubled, is the best way to go. it's a familiar convention, even with the doubling.
我认为使用这些字母是最好的方法。这是一个熟悉的习惯,即使是加倍。
there's a lot to say for sticking with conventions. it makes things a lot more readable.
对于遵守惯例有很多要说的。它让事情变得更有可读性。
#20
0
I've started using perlisms in php.
我已经开始在php中使用perlisms。
if its a singular iteration, $_
is a good name for those who know its use.
如果它是一个单一的迭代,$_对于知道它使用的人来说是一个好名字。
#21
0
My habit is to use 't' - close to 'r' so it follows easily aftewr typing 'for'
我的习惯是使用“t”-接近“r”,所以它很容易就可以输入“for”
#22
0
If it is a simple counter, I stick to using 'i' otherwise, have name that denotes the context. I tend to keep the variable length to 4. This is mainly from code reading point of view, writing is doesn't count as we have auto complete feature.
如果它是一个简单的计数器,我就会使用“I”,否则,就有表示上下文的名称。我倾向于将变量长度保持为4。这主要是从代码阅读的角度来看,写作是不算数的,因为我们有自动完成的功能。
#23
0
I've started to use context-relevant loop variable names mixed with hungarian.
我已经开始使用上下文相关的循环变量名和匈牙利语混合。
When looping through rows, I'll use iRow
. When looping through columns I'll use iCol
. When looping through cars I'll use iCar
. You get the idea.
当循环通过行时,我将使用iRow。当循环通过列时,我将使用iCol。当你在车里盘旋的时候,我会用iCar。你懂的。
#24
0
for numerical computations, matlab, and the likes of it, dont use i, j
对于数值计算,matlab,等等,不用i, j。
these are reserved constants, but matlab wont complain.
这些是保留的常量,但matlab不会抱怨。
My personal favs are
我个人的比如是
index first,second counter count
指数第一,第二计数器计数
#25
0
My favorite convention for looping over a matrix-like set is to use x+y as they are used in cartesian coordinates:
我最喜欢用x+y作为矩阵的循环,因为它们在笛卡尔坐标系中使用:
for x in width:
for y in height:
do_something_interesting(x,y)
#26
0
I usually use:
我通常使用:
for(lcObject = 0; lcObject < Collection.length(); lcObject++)
{
//do stuff
}
#27
0
For integers I use int index, unless it's nested then I use an Index suffix over what's being iterated like int groupIndex and int userIndex.
对于整数,我使用int索引,除非它是嵌套的,然后我使用一个索引后缀来遍历像int groupIndex和int userIndex这样的迭代。
#28
0
In Python, I use i, j, and k if I'm only counting times through. I use x, y, and z if the iteration count is being used as an index. If I'm actually generating a series of arguments, however, I'll use a meaningful name.
在Python中,我使用I、j和k,如果我只是计算时间。如果迭代计数被用作索引,我将使用x、y和z。如果我实际上生成了一系列的参数,我将使用一个有意义的名称。