gpt4 book ai didi

c++ - 是否需要 "do {...} while ( )"循环?

转载 作者:IT老高 更新时间:2023-10-28 12:11:17 24 4
gpt4 key购买 nike

Bjarne Stroustrup(C++ 创建者)曾经说过,他避免使用“do/while”循环,而是更喜欢按照“while”循环来编写代码。 [请参阅下面的报价。]

自从听到这个,我发现这是真的。你觉得呢?你有没有什么想法?有没有一个例子表明“do/while”比使用“while”更简洁、更容易理解?

针对一些答案:是的,我理解“do/while”和“while”之间的技术区别。这是一个关于可读性和结构化代码涉及循环的更深层次的问题。

让我问另一种方式:假设你被禁止使用“do/while” - 有没有一个现实的例子让你别无选择,只能使用“while”编写不干净的代码?

来自“C++ 编程语言”,6.3.3:

In my experience, the do-statement is a source of errors and confusion. The reason is that its body is always executed once before the condition is evaluated. However, for the body to work correctly, something very much like the condition must hold even the first time through. More often than I would have guessed, I have found that condition not to hold as expected either when the program was first written and tested, or later after the code preceding it has been modified. I also prefer the condition "up front where I can see it." Consequently, I tend to avoid do-statements. -Bjarne

避免 do/while 循环是 C++ Core Guidelines 中包含的建议。如ES.75, avoid do-statements .

最佳答案

是的,我同意 do while 循环可以重写为 while 循环,但我不同意总是使用 while 循环更好。 do while 总是至少运行一次,这是一个非常有用的属性(最典型的例子是输入检查(从键盘))

#include <stdio.h>

int main() {
char c;

do {
printf("enter a number");
scanf("%c", &c);

} while (c < '0' || c > '9');
}

这当然可以重写为 while 循环,但这通常被视为更优雅的解决方案。

关于c++ - 是否需要 "do {...} while ( )"循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/994905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com