是否有过需要一个"做好{...}而()"循环? [英] Is there ever a need for a "do {...} while ( )" loop?

查看:159
本文介绍了是否有过需要一个"做好{...}而()"循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bjarne的Stroustrup的(C ++创建者)曾经说过,他避免了做/而循环,prefers写code在while循环的角度来代替。 [参见下面的报价。]

由于听到这话,我发现这是真的。你怎么看?有一个例子,其中一个做/而更干净,更容易比你用来理解,而呢?

在回应一些问题的答案:是的,我明白了做/而和,而之间的技术差异。这是关于可读性和结构code,涉及循环一个更深层次的问题。

让我问另一种方式:假设你正在使用做/而禁 - 有一个现实的例子,这将给你别无选择,只能使用,而

写不洁code?

从C ++程序设计语言,6.3.3:


  

在我的经验中,DO-说法是错误和混乱的根源。其原因是,被评为条件之前它的身体总是执行一次。然而,对于身体能够正常工作,东西非常像的条件必须持有甚至通过第一次。更多的时候比我早就猜到,我发现情况不抱预期或者当首次编写并测试该计划,还是后来的code preceding已被修改了。 我也$​​ P $ PFER条件前面在那里我可以看到它。因此,我倾向于避免做陈述。 -Bjarne



解决方案

是的,我同意,do-whil​​e循环可以重写while循环,但我不同​​意它总是使用whil​​e循环更好。做而总是至少运行一次,这是一个非常有用的属性。

(最典型的例子是输入(通过键盘)检查)

 的#include<&stdio.h中GT;诠释主(){
    焦炭℃;    做{
        的printf(请输入一个数字);
        scanf函数(%C,和C);    }而(C<'0'|| C>'9');
}

当然,这可以改写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.]

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?

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.

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"?

From "The C++ Programming Language", 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

解决方案

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'); 
}

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

这篇关于是否有过需要一个&QUOT;做好{...}而()&QUOT;循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆