简体   繁体   English

为什么 c++(和大多数其他语言)同时具有“for”和“while”循环?/你可以用一种类型做什么而你不能用另一种类型做什么?

[英]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; switchesif怎么样? 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.

相关问题 你可以在C ++中嵌入循环(在彼此中) - Can you embed for loops (in each other) in C++ 动态C ++与其他语言-在不知道类型的情况下无法在对象上调用方法 - Dynamic C++ vs other languages - can't call a method on an object without knowing the type 在 Windows 中,您能否以编程方式 (C++) 检测哪些 DLL 已被其他正在运行的程序加载? - In Windows, can you programmatically (C++) detect which DLLs have been loaded by other running programs? 您可以在C ++中动态创建for循环吗? - Can you create for loops dynamically in C++? 你能在 C++ 的其他函数中使用函数吗? [等候接听] - Can you use functions within other functions in C++? [on hold] C++:对于两个带有 do-while 循环的不同函数,为什么 x+=y 在一个 function 中给出与 x=x+y 相同的结果,而在另一个中却不是? - C++: For two different functions with do-while loops, why does x+=y give the same result as x=x+y in one function but not the other? 在 c 或 c++ 中,循环可以同时包含“do”和“while”部分吗? - In c or c++ can a loop have both "do" and "while" sections? 与Qt开发的其他语言相比,C ++有什么优势? - What advantages does C++ have over other languages for Qt development? 为什么不能在 C++ 中有一个非常量 char*? - Why can't you have a non-const char* in C++? 为什么我不能使C ++中的对象具有作为其他对象的数据成员? - Why can't I make objects in C++ have data-members that are other objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM