问题描述
看起来像
while( condition ) {
//do stuff
}
完全等同于
for( ; condition; ) {
//do stuff
}
是否有任何理由使用后者而不是前者?
Is there any reason to use the latter instead of the former?
推荐答案
据我所知,没有好的理由.您通过使用不增加任何内容的 for 循环故意误导人们.
There's no good reason as far as I know. You're intentionally misleading people by using a for-loop that doesn't increment anything.
更新:
根据 OP 对该问题的评论,我可以推测您如何在实际代码中看到这样的构造.我以前见过(并使用过)这个:
Based on the OP's comment to the question, I can speculate on how you might see such a construct in real code. I've seen (and used) this before:
lots::of::namespaces::container::iterator iter = foo.begin();
for (; iter != foo.end(); ++iter)
{
// do stuff
}
但这就是我将事情排除在 for 循环之外的范围.也许您的项目曾经有一个看起来像这样的循环.如果在循环中间添加删除容器元素的代码,则可能必须仔细控制 iter
的递增方式.这可能导致代码如下所示:
But that's as far as I'll go with leaving things out of a for-loop. Perhaps your project had a loop that looked like that at one time. If you add code that removes elements of a container in the middle of the loop, you likely have to control carefully how iter
is incremented. That could lead to code that looks like this:
for (; iter != foo.end(); )
{
// do stuff
if (condition)
{
iter = foo.erase(iter);
}
else
{
++iter;
}
}
然而,这不是不花 5 秒时间将其更改为 while 循环的借口.
However, that's no excuse for not taking the five seconds needed to change it into a while-loop.
这篇关于有什么理由在 C++ 中用 for(;condition;) 替换 while(condition)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!