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

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

问题描述

可能的重复:
使用 for 循环还是 while 循环进行迭代?
C 中的循环 - for() 或 while() - 这是最好?

什么时候应该使用 for 循环而不是 while 循环?

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

推荐答案

就您而言,除了在 for 循环中少一行代码之外,您并没有得到太多好处.

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.

最后的想法:
更重要的一点.两者之间存在语义差异.一般而言,While 循环意味着无限次迭代.(即,直到文件被读取......无论其中有多少行),并且 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天全站免登陆