Any reason to replace while(condition) with for(;condition;) in C++?(有什么理由在 C++ 中用 for(;condition;) 替换 while(condition)?)
问题描述
看起来像
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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有什么理由在 C++ 中用 for(;condition;) 替换 while(condition)?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01