循环变量的理想变量命名约定是什么?
如果您正在编写一个简单小循环,您应该为计数器命名什么?
提供示例循环!
If you are writing a simple little loop, what should you name the counter?
Provide example loops!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(28)
我总是使用有意义的名称,除非它是单级循环,并且该变量除了“我经历过这个循环的次数”之外没有任何意义,在这种情况下我使用
我。
使用有意义的名称时:
示例 - 发现错误
使用单个字母在此嵌套循环中查找错误可能会很棘手:
而使用有意义的名称时会更容易:
为什么
row_num
? - 被拒绝的替代方案为了回应其他一些答案和评论,这些是使用
row_num
和col_num
的一些替代建议以及我选择不使用它们的原因:r
和c
:这比i
和j
稍好。 仅当我的组织的标准是单字母变量为整数并且始终为等效描述性名称的第一个字母时,我才会考虑使用它们。 如果函数中有两个名称以“r”开头的变量,系统就会崩溃,即使其他以“r”开头的对象出现在代码中的任何位置,可读性也会受到影响。rr
和cc
:这对我来说看起来很奇怪,但我不习惯双字母循环风格多变。 如果它是我组织中的标准,那么我想它会比r
和c
稍好一些。row
和col
:乍一看,这似乎比row_num
和 < code>col_num,并且同样具有描述性。 然而,我希望像“行”和“列”这样的裸名词来指代结构、对象或指向它们的指针。 如果row
可能意味着行结构本身,或行号,那么就会导致混乱。iRow
和iCol
:这传达了额外的信息,因为i
可以表示它是循环计数器,而Row
和Col
告诉您正在计数的内容。 然而,我更喜欢能够阅读几乎是英文的代码:我接受的 row_num 的替代方案是 row_idx:“索引”一词唯一指代数组位置,除非应用程序的领域是数据库引擎设计、金融市场或类似领域。
我上面的例子已经尽可能小了,因此有些人可能看不到描述性命名变量的意义,因为他们可以一次性将整个函数记住。 然而,在实际代码中,函数会更大,逻辑会更复杂,因此得体的名称对于提高可读性和避免错误变得更加重要。
总之,我对所有变量命名(不仅仅是循环)的目标是完全明确。 如果任何人读取了我的代码的任何部分并且无法立即弄清楚变量的用途,那么我就失败了。
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
.When using meaningful names:
Example - spot the bug
It can be tricky to find the bug in this nested loop using single letters:
whereas it is easier when using meaningful names:
Why
row_num
? - rejected alternativesIn response to some other answers and comments, these are some alternative suggestions to using
row_num
andcol_num
and why I choose not to use them: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.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
.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.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";iRow < MAX_COLS
at best reads as "the integer loop counter for the row is less than the maximum (number of) columns".An alternative to
row_num
I would accept isrow_idx
: the word "index" uniquely refers to an array position, unless the application's domain is in database engine design, financial markets or similar.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.
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.
1) 对于普通的旧式小循环 - i、j、k - 如果您需要超过 3 层的嵌套循环,这意味着算法非常具体且复杂,或者您应该考虑重构代码。
Java 示例:
2) 对于像
for(Element element: ElementsList)
这样的新样式 java 循环,最好使用正常的有意义的名称Java 示例:
3) 如果您使用的语言可以,请转换使用迭代器的循环
Java 迭代器示例:单击此处
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, or you should consider refactoring the code.
Java Example:
2) For the new style java loops like
for(Element element: ElementsList)
it is better to use normal meanigful nameJava Example:
3) If it is possible with the language you use, convert the loop to use iterator
Java Iterator Example: click here
示例:。 。 。 在 Java 中
非迭代循环:
非嵌套循环:。 。 。 索引是一个值。
嵌套循环:。 。 。 区分指数有助于理解。
foreach
循环: . 。 。对象
需要一个名称。迭代循环:
for
循环: . 。 。 迭代器引用对象。 它既不是迭代器,也不是迭代器。 一个索引,也不是一个指数。while
循环: . 。 。 限制迭代器的范围。Examples: . . . In Java
Non-Iterative Loops:
Non-Nested Loops: . . . The Index is a value.
Nested Loops: . . . Differentiating Indices lends to comprehension.
foreach
Loops: . . . AnObject
needs a name.Iterative Loops:
for
Loops: . . . Iterators reference Objects. An Iterator it is neither; an Index, nor an Indice.while
Loops: . . . Limit the scope of the Iterator.我的经验是大多数人使用单个字母,例如:
我
,j
,k
,...
或者
x
,y
,或者
r
,c
(用于行/列)或者
w
,h
(宽度/高度)等等。
但是我很久以前就学会了一个很好的选择,并且从那时起就一直使用它:双字母变量。
如果好处不是很明显:在代码中搜索任何单个字母都会发现许多不是您正在寻找的内容。 字母
i
在代码中经常出现,但它不是您要查找的变量。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.
But I learned a great alternative a long time ago, and have used it ever since: double letter variables.
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.始终尝试将变量命名为有意义且符合上下文的名称。
如果您无法决定,请使用“索引”,这样其他人(也许是您!)就可以更轻松地单击它以进行稍后的重构。
Paul Stephenson请参阅此答案一个例子。
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.
i
如果我有一个嵌套循环,那么还有
j
。这种约定非常常见,以至于如果您在代码块中遇到一个看不到开头的变量
i
,您仍然可以立即认出它是什么。i
if I have a nested loop then also
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、j、k (或 r 和 c 表示行-列循环)。 如果您在一个方法中需要三个以上的循环变量,则该方法可能太长且太复杂,并且您的代码可能会将方法拆分为更多方法,并且正确命名它们。
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、ii、iii、iv、v...但从未高于 iii。
I use i, ii, iii, iv, v ... Never got higher than iii, though.
仅当循环计数器是索引时我才使用单个字母。 我喜欢双字母背后的想法,但它使代码非常难以阅读。
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.
如果计数器用作容器的索引,我使用
i
、j
、k
。如果要使用它来迭代一个范围(或执行一定数量的迭代),我经常使用
n
。 不过,如果需要嵌套,我通常会恢复为i
、j
、k
。在提供
foreach
样式构造的语言中,我通常这样写:我认为有些人会因为将
widget
命名为与widgets
如此类似而责备我code>,但我发现它很有可读性。If the counter is to be used as an index to a container, I use
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 toi
,j
,k
.In languages which provide a
foreach
-style construct, I usually write like this:I think some people will tell me off for naming
widget
so similarly towidgets
, but I find it quite readable.我长期以来一直使用 i/j/k 命名方案。 但最近我开始采用一种更连续的命名方法。
我已经按其含义命名了所有变量,那么为什么不以相同的确定性方式命名循环变量呢?
根据要求提供几个示例:
如果您需要循环遍历项目集合。
但我尝试避免正常的 for 循环,因为我倾向于想要列表中的真实项目并使用它,而不是列表中的实际位置。 而不是以 a: 开头 for 块
因此,我尝试使用该语言的 foreach 结构, 。 这改变了.
这
使得它更容易阅读,因为只表达了代码的真正含义(处理列表中的项目),而不是我们想要处理项目的方式(保留当前项目的索引并增加它直到它到达列表的长度,从而意味着项目集合的结束)。
我唯一一次仍然使用单字母变量是当我循环维度时。 但随后我会使用 x、y,有时还会使用 z。
I have long used the i/j/k naming scheme. But recently I've started to adapt a more consequent naming method.
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.
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:
I try to use the foreach construct of the language. which transforms the.
into
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.
就像之前的海报一样,我也使用 ii, jj,.. 主要是因为在许多字体中,单个 i 看起来与 1 非常相似。
Like a previous poster, I also use ii, jj,.. mainly because in many fonts a single i looks very similar to 1.
我使用“计数器”或“循环”作为变量名。 现代 IDE 通常会完成单词补全,因此较长的变量名称使用起来并不那么繁琐。 此外,根据变量的功能命名变量可以让维护代码的程序员清楚地了解您的意图。
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.
Perl 标准
在 Perl 中,内循环的标准变量名称是 $_。 for、foreach 和 while 语句默认使用此变量,因此您无需声明它。 通常,$_ 可以读作中性通用代词“it”。 因此,一个相当标准的循环可能看起来像:
用英语翻译为:
然而,更常见的是根本不使用变量。 许多 Perl 函数和运算符默认为 $_:
英文:
这也是计数器的标准。 (但是计数器在 Perl 中的使用频率远远低于其他语言(例如 C)。 因此,要打印 1 到 100 之间的整数的平方:
由于只有一个循环可以使用 $_ 变量,因此通常在最内层循环中使用它。 这种用法与英语通常的用法相符:
在 Perl 中:
如上所述,最好在外循环中使用更长的描述性名称,因为在很长的代码块中很难记住通用循环变量名称的真正含义。
有时,使用较短的、非描述性的通用名称(例如 $i、$j 和 $k)是有意义的,而不是使用$_ 或描述性名称。 例如,匹配已发布算法中使用的变量非常有用,例如叉积。
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:
In English, that translates to:
Even more common, however, is to not use a variable at all. Many Perl functions and operators default to $_:
In English:
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:
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:
In Perl:
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.
第一条规则是变量名的长度应与变量的范围匹配。 第二条规则是有意义的名称会使错误变得更浅。 第三条规则是,如果您想为变量名称添加注释,那么您选择了错误的变量名称。 最终规则是像你的队友那样做,只要它不违背之前的规则即可。
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.
@JustMike。 。 。 一些 C 示例:。 。 。 伴随 Java 循环。
非嵌套循环: 。 。 。 尽可能限制范围
嵌套循环:。 。 。 同上
这个布局的一个好处是它在没有注释的情况下读起来很糟糕,从而鼓励了它们。
它可能很冗长,但就我个人而言,这就是我在 C 中执行循环的方式。
另外:我开始时确实使用了“index”和“idx”,但这通常被我的同行更改为“i”。
@JustMike . . . A FEW C EXAMPLES: . . . to accompany the Java ones.
NON-NESTED loop: . . . limiting scope where possible
NESTED loop: . . . ditto
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.
对于数值计算,matlab 等,不要使用 i,j
这些是保留常量,但 matlab 不会抱怨。
我个人最喜欢的是
索引
第一秒
柜台
数数
for numerical computations, matlab, and the likes of it, dont use i, j
these are reserved constants, but matlab wont complain.
My personal favs are
index
first,second
counter
count
无论您选择什么,请在代码中一致地使用相同的索引,只要它具有相同的含义。 例如,要遍历数组,您可以使用
i
、jj
、kappa
等,但始终以相同的方式进行操作:最佳实践是使循环的这一部分在整个代码中看起来相同(包括始终使用
count
作为限制),以便它成为您可以在心里跳过以集中注意力的习惯用法代码的核心部分,即循环体。类似地,例如,如果您正在遍历一个二维像素数组,您可以
在编写此类循环的每个地方都以相同的方式编写 Just do it。
您希望您的读者能够忽略无聊的设置,并看到您在实际循环中所做的事情的辉煌。
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: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
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.
像往常一样,Steve McConnell 的代码完整在这方面提供了一些极好的建议。 相关页面(无论如何在第一版中)是 340 和 341。绝对建议任何有兴趣改进循环编码的人看看这个。 麦康奈尔推荐了有意义的循环计数器名称,但人们应该自己阅读他所说的内容,而不是依赖我的薄弱总结。
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.
我也使用双字母约定。 ii、jj、kk。 你可以 grep 那些并且不会出现一堆不需要的匹配项。
我认为使用这些字母,即使它们是双倍的,也是最好的方法。 这是一个熟悉的惯例,即使是双倍的。
关于遵守惯例,有很多话要说。 它使事情更具可读性。
i also use the double-letter convention. ii, jj, kk. you can grep those and not come up with a bunch of unwanted matches.
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.
我开始在 php 中使用 perlisms。
如果它是一个单一的迭代,对于那些知道它的用途的人来说,
$_
是一个好名字。I've started using perlisms in php.
if its a singular iteration,
$_
is a good name for those who know its use.我的习惯是使用“t”——靠近“r”,因此在输入“for”后很容易跟随
My habit is to use 't' - close to 'r' so it follows easily aftewr typing 'for'
如果它是一个简单的计数器,我坚持使用“i”,否则,使用表示上下文的名称。 我倾向于将变量长度保持为 4。这主要是从代码读取的角度来看,写入不算,因为我们有自动完成功能。
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.
我开始使用与上下文相关的循环变量名称与 匈牙利语 混合。
循环遍历行时,我将使用
iRow
。 循环遍历列时,我将使用iCol
。 当循环浏览汽车时,我将使用iCar
。 你明白了。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 useiCol
. When looping through cars I'll useiCar
. You get the idea.我最喜欢的循环类似矩阵集合的约定是使用 x+y,因为它们在笛卡尔坐标中使用:
My favorite convention for looping over a matrix-like set is to use x+y as they are used in cartesian coordinates:
我通常使用:
I usually use:
对于整数,我使用 int index,除非它是嵌套的,否则我会在迭代的内容上使用 Index 后缀,例如 int groupIndex 和 int userIndex。
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.
在 Python 中,如果我只是计算次数,我会使用 i、j 和 k。 如果迭代计数用作索引,我会使用 x、y 和 z。 然而,如果我实际上生成一系列参数,我将使用一个有意义的名称。
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.