循环变量的理想变量命名约定是什么?

发布于 2024-07-06 09:05:11 字数 79 浏览 7 评论 0原文

如果您正在编写一个简单小循环,您应该为计数器命名什么?

提供示例循环!

If you are writing a simple little loop, what should you name the counter?

Provide example loops!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

罗罗贝儿 2024-07-13 09:05:11

我总是使用有意义的名称,除非它是单级循环,并且该变量除了“我经历过这个循环的次数”之外没有任何意义,在这种情况下我使用 我。

使用有意义的名称时:

  • 代码对于阅读代码的同事来说更容易理解,
  • 更容易发现循环逻辑中的错误,并且
  • 文本搜索变量名称以返回对相同数据进行操作的相关代码片段更可靠。

示例 - 发现错误

使用单个字母在此嵌套循环中查找错误可能会很棘手:

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;
}

而使用有意义的名称时会更容易:

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;
}

为什么 row_num? - 被拒绝的替代方案

为了回应其他一些答案和评论,这些是使用 row_numcol_num 的一些替代建议以及我选择不使用它们的原因:

  • rc:这比 ij 稍好。 仅当我的组织的标准是单字母变量为整数并且始终为等效描述性名称的第一个字母时,我才会考虑使用它们。 如果函数中有两个名称以“r”开头的变量,系统就会崩溃,即使其他以“r”开头的对象出现在代码中的任何位置,可读性也会受到影响。
  • rrcc:这对我来说看起来很奇怪,但我不习惯双字母循环风格多变。 如果它是我组织中的标准,那么我想它会比 rc 稍好一些。
  • rowcol:乍一看,这似乎比 row_num 和 < code>col_num,并且同样具有描述性。 然而,我希望像“行”和“列”这样的裸名词来指代结构、对象或指向它们的指针。 如果row可能意味着行结构本身,行号,那么就会导致混乱。
  • iRowiCol:这传达了额外的信息,因为 i 可以表示它是循环计数器,而 RowCol 告诉您正在计数的内容。 然而,我更喜欢能够阅读几乎是英文的代码:
    • <代码>row_num < MAX_COLS 读作“行数数量小于最大imum(数量)umns";
    • <代码>iRow < MAX_COLS 最多可以理解为“整数循环计数器小于最大值” imum(columns 的数量”。
    • 这可能是个人的事情,但我更喜欢第一次阅读。

我接受的 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:

  • the code is more understandable to colleagues reading your code,
  • it's easier to find bugs in the loop logic, and
  • 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:

  • r and c: This is slightly better than i and j. 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 and cc: 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 than r and c.
  • row and col: At first glance this seems more succinct than row_num and col_num, and just as descriptive. However, I would expect bare nouns like "row" and "column" to refer to structures, objects or pointers to these. If row could mean either the row structure itself, or a row number, then confusion will result.
  • iRow and iCol: This conveys extra information, since i can mean it's a loop counter while Row and Col 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".
    • It may be a personal thing but I prefer the first reading.

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.

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.

も星光 2024-07-13 09:05:11

1) 对于普通的旧式小循环 - i、j、k - 如果您需要超过 3 层的嵌套循环,这意味着算法非常具体且复杂,或者您应该考虑重构代码。

Java 示例:

for(int i = 0; i < ElementsList.size(); i++) {
  Element element = ElementsList.get(i);
  someProcessing(element);
  ....
}

2) 对于像 for(Element element: ElementsList) 这样的新样式 java 循环,最好使用正常的有意义的名称

Java 示例:

for(Element element: ElementsList) {
  someProcessing(element);
  ....
}

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:

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

Java Example:

for(Element element: ElementsList) {
  someProcessing(element);
  ....
}

3) If it is possible with the language you use, convert the loop to use iterator

Java Iterator Example: click here

誰認得朕 2024-07-13 09:05:11

示例:。 。 。 在 Java 中

非迭代循环:

非嵌套循环:。 。 。 索引是一个值。

。 。 。 使用 i就像在代数中一样,是最常见的做法。 。 .

for (int i = 0; i < LOOP_LENGTH; i++) {

    // LOOP_BODY
}

嵌套循环:。 。 。 区分指数有助于理解。

。 。 。 使用描述性后缀。 。 .

for (int iRow = 0; iRow < ROWS; iRow++) {

    for (int iColumn = 0; iColumn < COLUMNS; iColumn++) {

        // LOOP_BODY
    }
}

foreach 循环: . 。 。 对象需要一个名称。

。 。 。 使用描述性名称。 。 .

for (Object something : somethings) {

    // LOOP_BODY
}

迭代循环:

for 循环: . 。 。 迭代器引用对象。 它既不是迭代器,也不是迭代器。 一个索引,也不是一个指数。

。 。 。 iter 缩写迭代器的用途。 。 .

for (Iterator iter = collection.iterator(); iter.hasNext(); /* N/A */) {

    Object object = iter.next();

    // LOOP_BODY
}

while 循环: . 。 。 限制迭代器的范围。

。 。 。 评论循环目的。 。 .

/* LOOP_DESCRIPTION */ {

    Iterator iter = collection.iterator();

    while (iter.hasNext()) {

        // LOOP_BODY
    }
}

最后一个例子在没有注释的情况下读起来很糟糕,从而鼓励了他们。
它可能很冗长,但在 C 中的范围限制循环中很有用。

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 . . .

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.

. . . 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.

. . . iter abreviates an Iterators purpose . . .

for (Iterator iter = collection.iterator(); iter.hasNext(); /* N/A */) {

    Object object = iter.next();

    // LOOP_BODY
}

while Loops: . . . Limit the scope of the Iterator.

. . . 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.

请持续率性 2024-07-13 09:05:11

我的经验是大多数人使用单个字母,例如:

j,
k
...
或者
x
y
或者
r
c(用于行/列)
或者
w
h(宽度/高度)
等等。

但是我很久以前就学会了一个很好的选择,并且从那时起就一直使用它:双字母变量。

// 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;
    }                             ●        }
}                                 ●    }

如果好处不是很明显:在代码中搜索任何单个字母都会发现许多不是您正在寻找的内容。 字母 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.

// 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.

淡淡離愁欲言轉身 2024-07-13 09:05:11

始终尝试将变量命名为有意义且符合上下文的名称。

如果您无法决定,请使用“索引”,这样其他人(也许是您!)就可以更轻松地单击它以进行稍后的重构。

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.

高跟鞋的旋律 2024-07-13 09:05:11

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.

書生途 2024-07-13 09:05:11

我使用 ijk (或 rc 表示行-列循环)。 如果您在一个方法中需要三个以上的循环变量,则该方法可能太长且太复杂,并且您的代码可能会将方法拆分为更多方法,并且正确命名它们。

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.

黑寡妇 2024-07-13 09:05:11

我使用 i、ii、iii、iv、v...但从未高于 iii。

I use i, ii, iii, iv, v ... Never got higher than iii, though.

娇女薄笑 2024-07-13 09:05:11

仅当循环计数器是索引时我才使用单个字母。 我喜欢双字母背后的想法,但它使代码非常难以阅读。

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.

愛放△進行李 2024-07-13 09:05:11

如果计数器用作容器的索引,我使用 ijk

如果要使用它来迭代一个范围(或执行一定数量的迭代),我经常使用n。 不过,如果需要嵌套,我通常会恢复为 ijk

在提供 foreach 样式构造的语言中,我通常这样写:

foreach widget in widgets do
  foo(widget)
end

我认为有些人会因为将 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 to i, j, k.

In languages which provide a foreach-style construct, I usually write like this:

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.

山有枢 2024-07-13 09:05:11

我长期以来一直使用 i/j/k 命名方案。 但最近我开始采用一种更连续的命名方法。

我已经按其含义命名了所有变量,那么为什么不以相同的确定性方式命名循环变量呢?

根据要求提供几个示例:

如果您需要循环遍历项目集合。

for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)
{
    ...
}

但我尝试避免正常的 for 循环,因为我倾向于想要列表中的真实项目并使用它,而不是列表中的实际位置。 而不是以 a: 开头 for 块

Item currentItem = list[currentItemIndex];

因此,我尝试使用该语言的 foreach 结构, 。 这改变了.

for (int currentItemIndex = 0; currentItemIndex < list.Length; currentItemIndex++)
{
    Item currentItem = list[currentItemIndex];
    ...
}

foreach (Item currentItem in list)
{
   ...
}

使得它更容易阅读,因为只表达了代码的真正含义(处理列表中的项目),而不是我们想要处理项目的方式(保留当前项目的索引并增加它直到它到达列表的长度,从而意味着项目集合的结束)。

我唯一一次仍然使用单字母变量是当我循环维度时。 但随后我会使用 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.

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:

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.

你的心境我的脸 2024-07-13 09:05:11

就像之前的海报一样,我也使用 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.

空心↖ 2024-07-13 09:05:11

我使用“计数器”或“循环”作为变量名。 现代 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.

幸福不弃 2024-07-13 09:05:11

Perl 标准

在 Perl 中,内循环的标准变量名称是 $_forforeachwhile 语句默认使用此变量,因此您无需声明它。 通常,$_ 可以读作中性通用代词“it”。 因此,一个相当标准的循环可能看起来像:

foreach (@item){
    $item_count{$_}++;
}

用英语翻译为:

对于每个项目,增加它的 item_count。

然而,更常见的是根本不使用变量。 许多 Perl 函数和运算符默认为 $_

for (@item){
    print;
}

英文:

对于[每个]项目,打印[它]。

这也是计数器的标准。 (但是计数器在 Perl 中的使用频率远远低于其他语言(例如 C)。 因此,要打印 1 到 100 之间的整数的平方:

for (1..100){
    print "$_*$_\n";
}

由于只有一个循环可以使用 $_ 变量,因此通常在最内层循环中使用它。 这种用法与英语通常的用法相符:

对于每辆车,查看每个轮胎并检查其压力。

在 Perl 中:

foreach $car (@cars){
    for (@{$car->{tires}}){
        check_pressure($_);
    }
}

如上所述,最好在外循环中使用更长的描述性名称,因为在很长的代码块中很难记住通用循环变量名称的真正含义。

有时,使用较短的、非描述性的通用名称(例如 $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:

foreach (@item){
    $item_count{$_}++;
}

In English, that translates to:

For each item, increment it's item_count.

Even more common, however, is to not use a variable at all. Many Perl functions and operators default to $_:

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:

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:

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.

万劫不复 2024-07-13 09:05:11

第一条规则是变量名的长度应与变量的范围匹配。 第二条规则是有意义的名称会使错误变得更浅。 第三条规则是,如果您想为变量名称添加注释,那么您选择了错误的变量名称。 最终规则是像你的队友那样做,只要它不违背之前的规则即可。

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.

各空 2024-07-13 09:05:11

@JustMike。 。 。 一些 C 示例:。 。 。 伴随 Java 循环。

非嵌套循环: 。 。 。 尽可能限制范围

/*LOOP_DESCRIPTION*/ {

    int i;

    for (i = 0; i < LOOP_LENGTH; i++) {

        // loop body
    }  
}

嵌套循环:。 。 。 同上

/*LOOP_DESCRIPTION*/ {

    int row, column;

    for (row = 0; row < ROWS; row++) {

        for (column = 0; column < COLUMNS; column++) {

            // loop body
        }
    }  
}

这个布局的一个好处是它在没有注释的情况下读起来很糟糕,从而鼓励了它们。
它可能很冗长,但就我个人而言,这就是我在 C 中执行循环的方式。

另外:我开始时确实使用了“index”和“idx”,但这通常被我的同行更改为“i”。

@JustMike . . . A FEW C EXAMPLES: . . . to accompany the Java ones.

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.

纵山崖 2024-07-13 09:05:11

对于数值计算,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

七禾 2024-07-13 09:05:11

无论您选择什么,请在代码中一致地使用相同的索引,只要它具有相同的含义。 例如,要遍历数组,您可以使用 ijjkappa 等,但始终以相同的方式进行操作:

for (i = 0; i < count; i++) ...

最佳实践是使循环的这一部分在整个代码中看起来相同(包括始终使用 count 作为限制),以便它成为您可以在心里跳过以集中注意力的习惯用法代码的核心部分,即循环体。

类似地,例如,如果您正在遍历一个二维像素数组,您可以

for (y = 0; y < height; y++)
  for (x = 0; x < width; x++)
    ...

在编写此类循环的每个地方都以相同的方式编写 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:

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.

人│生佛魔见 2024-07-13 09:05:11

像往常一样,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.

怂人 2024-07-13 09:05:11

我也使用双字母约定。 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.

维持三分热 2024-07-13 09:05:11

我开始在 php 中使用 perlisms。

如果它是一个单一的迭代,对于那些知道它的用途的人来说,$_是一个好名字。

I've started using perlisms in php.

if its a singular iteration, $_ is a good name for those who know its use.

酷炫老祖宗 2024-07-13 09:05:11

我的习惯是使用“t”——靠近“r”,因此在输入“for”后很容易跟随

My habit is to use 't' - close to 'r' so it follows easily aftewr typing 'for'

烟酒忠诚 2024-07-13 09:05:11

如果它是一个简单的计数器,我坚持使用“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.

逆夏时光 2024-07-13 09:05:11

我开始使用与上下文相关的循环变量名称与 匈牙利语 混合。

循环遍历行时,我将使用 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 use iCol. When looping through cars I'll use iCar. You get the idea.

夏了南城 2024-07-13 09:05:11

我最喜欢的循环类似矩阵集合的约定是使用 x+y,因为它们在笛卡尔坐标中使用:

for x in width:
    for y in height:
        do_something_interesting(x,y)

My favorite convention for looping over a matrix-like set is to use x+y as they are used in cartesian coordinates:

for x in width:
    for y in height:
        do_something_interesting(x,y)
南风几经秋 2024-07-13 09:05:11

我通常使用:

for(lcObject = 0; lcObject < Collection.length(); lcObject++)
{
   //do stuff
}

I usually use:

for(lcObject = 0; lcObject < Collection.length(); lcObject++)
{
   //do stuff
}
如果没有你 2024-07-13 09:05:11

对于整数,我使用 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.

你好,陌生人 2024-07-13 09:05:11

在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文