是否需要“do {...} while ()"?环形?

时间:2022-11-21
本文介绍了是否需要“do {...} while ()"?环形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

Bjarne Stroustrup(C++ 创造者)曾经说过他避免do/while"循环,并且更喜欢根据while"来编写代码.循环代替.[见下面的引用.]

Bjarne Stroustrup (C++ creator) once said that he avoids "do/while" loops, and prefers to write the code in terms of a "while" loop instead. [See quote below.]

自从听到这个消息后,我发现这是真的.你怎么看?是否有一个do/while"的例子?比使用while"更清晰、更容易理解.取而代之?

Since hearing this, I have found this to be true. What are your thoughts? Is there an example where a "do/while" is much cleaner and easier to understand than if you used a "while" instead?

回应一些答案:是的,我理解do/while"和do/while"之间的技术差异.和同时".这是一个涉及循环的可读性和结构化代码的更深层次的问题.

In response to some of the answers: yes, I understand the technical difference between "do/while" and "while". This is a deeper question about readability and structuring code involving loops.

让我换个方式问:假设你被禁止使用do/while"- 是否有一个现实的例子,这会让你别无选择,只能使用while"编写不干净的代码?

Let me ask another way: suppose you were forbidden from using "do/while" - is there a realistic example where this would give you no choice but to write unclean code using "while"?

来自C++ 编程语言",6.3.3:

From "The C++ Programming Language", 6.3.3:

根据我的经验,do-statement 是错误和混乱的根源.原因是它的主体总是在评估条件之前执行一次.然而,为了让身体正常工作,即使第一次通过,也必须保持非常类似的情况.比我预想的更多的是,我发现无论是在程序第一次编写和测试时,还是在其前面的代码被修改之后,这种情况都不会像预期的那样保持.我也更喜欢在我可以看到的地方"的条件.因此,我倾向于避免使用 do 语句. -Bjarne

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++ 核心指南中的建议 作为 ES.75,避免do 语句.

Avoiding the do/while loop is a recommendation included in the C++ Core Guidelines as ES.75, avoid do-statements.

推荐答案

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

Yes I agree that do while loops can be rewritten to a while loop, however I disagree that always using a while loop is better. do while always get run at least once and that is a very useful property (most typical example being input checking (from keyboard))

#include <stdio.h>

int main() {
    char c;

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

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

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

This can of course be rewritten to a while loop, but this is usually viewed as a much more elegant solution.

这篇关于是否需要“do {...} while ()"?环形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何从交换机内部跳出循环? 下一篇:需要精确的线程睡眠.最大 1ms 误差

相关文章

最新文章