从 for 循环转换为 while 循环的正确方法是什么?
我有一个以下形式的 for 循环:
for (int i = from; i < to; i++) {
// do some code (I don't know exactly what, it is subject to change)
}
我想将其转换为 while 循环(主要是因为我想在循环内使用 i
的值来前后移动,而我的同事工人认为在 for 循环中这样做很容易出现问题,我倾向于同意他的观点)。所以我写了这样的东西:
int i = from;
while (i < to) {
try {
// do some code (I don't know exactly what, it is subject to change)
} finally {
i++;
}
}
这引起了一些大声的评论。我的理由是,您不知道循环内的代码做了什么 - 它可能(并且确实)有多个 continue
命令。
作为回应,他写道:
int i = from - 1;
while (++i < to) {
// do some code (I don't know exactly what, it is subject to change)
}
虽然行数较少,但我仍然认为我的代码更优雅 - 你觉得怎么样?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在循环结构中使用索引值很容易出现问题,无论循环结构是什么。
无论是 for 循环还是 while 循环都没有关系,关键是索引器最终会引导您做出循环终止的决定吗?
如果您确信索引器最终会导致实现退出条件,那么您应该关心的就是这,而不是是否使用 for 或 a while。
Playing with the value of your index while in a looping structure is prone to problems, no matter what the looping structure is.
It's not going to matter if it's a for loop or a while loop, the point is will the indexer eventually lead you to make a decision of loop termination?
If you're confident that you're indexer will eventually cause your exit condition to be achieved, then that is all you should be concerned with, not whether to use a for or a while.
这在大多数语言中是完全可以接受的。没有理由避免 for 循环。
This is perfectly acceptable in most languages. There is no reason to avoid a for loop.
在我看来,将其转换为: 可能更容易且更具可读性,
从而将循环的终止与变量增量分开。
如果我看到一个带有限制检查的循环(例如
i),我会倾向于假设有一个变量正在以(合理)一致的方式进行修改。你没有理由不能做你想做的事,但我会倾向于更具可读性和更预期的行为。
It seems to me that it may be easier and more readable to convert it to:
and thus separate the termination of the loop from the variable incrementation.
If I see a loop with a limit check (e.g.
i < limit
) I would tend to assume that there's a variable that is being modified in a (reasonably) consistent fashion. There's no reason why you can't do what you want, but I would lean towards the more readable and more expected behaviour.当您可以使用超级强大的
goto
做同样的事情(甚至更多!)时,为什么要为愚蠢的循环烦恼呢?如果您是那些减少
goto
的胆怯程序员之一,那么您可以尝试这样做:Why bother with silly loops when you can do the same (and much more!) with the uber-powerful
goto
?If you are one of those faint hearted programmers that diminish the
goto
, then you can try with this:最简单的方法是不转换为 while 循环,如下所示。
The easiest way to do this would be to not convert into a while loop, such as below.
回答关于我会选择哪个代码的问题;我选择你的更长的代码。阅读第一个(较长的)循环要容易得多。是的,我可以阅读第二个,但即使您有很多经验,您也必须看两遍才能知道该循环的作用。另外,编译器会很好地优化代码。
To answer the question about which code I would select; I choose your longer code. Its MUCH easier to read the first(longer) loop. And yes I can read the second but even if you have lots of experience you have to look twice to know what that loop does. Plus the compiler will optimize the code well enough.