[英]Why does c++(and most other languages) have both 'for' and 'while' loops?/What can you do with one type that you can't with the other?
Why do most programming languages have two or more types of loops with almost no difference?为什么大多数编程语言都有两种或两种以上几乎没有区别的循环? In c++, is one of the two better for specific tasks?
在 c++ 中,对于特定任务,两者中的哪一个更好? What about
switches
and if
's; switches
和if
怎么样? is there any difference there?那里有什么区别吗?
If not, then an answer about why they were implemented would be appreciated.如果没有,那么将不胜感激关于为什么实施它们的答案。
There is nothing that you can do with one type that you can't do with the other, because mechanical transformations exist between them:没有什么可以用一种类型做而不能用另一种类型做的,因为它们之间存在机械转换:
while (X) { body; }
can be written as可以写成
for (;X;) { body; }
and和
for (A;B;C) { body; }
can be written as可以写成
{ A; while (B) { body; C; } }
The only difference is readability.唯一的区别是可读性。 The for loop puts the update-expression
C
at the top of the loop, making it easier to recognize certain patterns like looping through a numeric range: for 循环将更新表达式
C
放在循环的顶部,使其更容易识别某些模式,例如在数字范围内循环:
for( i = 0; i < limit; ++i )
or following a linked list或遵循链表
for( ; ptr != nullptr; ptr = ptr->next )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.