为什么要使用for循环而不是while循环? [英] Why use a for loop instead of a while loop?

查看:824
本文介绍了为什么要使用for循环而不是while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:

使用for循环或while循环迭代?

在C - for()或while()中循环,这是BEST?

何时应使用代替循环而不是 loop?

When should one use a for loop instead of a while loop?

我认为以下循环是完全相同的,除了它们的语法。如果是,那么为什么要选择一个呢?

I think the following loops are identical, except for their syntax. If so, then why choose one over the other?

int i;
for (i = 0; i < arr.length; i++) {
  // do work
}

int i = 0;
while (i < arr.length) {
  // do work
  i++;
}


推荐答案

除了在中循环中少了一行代码,

In your case, you don't gain much besides one less line of code in the for loop.

然而,如果你声明循环像这样:

However, if you declare the loop like so:

for(int i = 0; i < x; i++)

您设法在循环范围内保留 i ,而不是让它逃脱

You manage to keep i within the scope of the loop, instead of letting it escape to the rest of the code.

此外,在while循环中,您有3个不同位置的变量声明,条件和增量。使用for循环,它在一个方便,易于阅读的地方。

Also, in a while loop, you have the variable declaration, the condition, and the increment in 3 different places. With the for loop, it is all in one convenient, easy-to-read place.

最后的想法:

一个更重要的注意事项。两者之间存在语义差异。虽然循环通常意味着具有不定数量的迭代。 (即,直到文件已经被读取,无论它有多少行),并且for循环应该有更确定的迭代次数。 (循环遍历集合中的所有元素,我们可以根据集合的大小进行计数。)

Last thought:
One more important note. There is a semantic difference between the two. While loops, in general, are meant to have an indefinite number of iterations. (ie. until the file has been read..no matter how many lines are in it), and for loops should have a more definite number of iterations. (loop through all of the elements in a collection, which we can count based on the size of the collection.)

这篇关于为什么要使用for循环而不是while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆