問題描述
Bjarne Stroustrup(C++ 創(chuàng)造者)曾經(jīng)說過他避免do/while"循環(huán),并且更喜歡根據(jù)while"來編寫代碼.循環(huán)代替.[見下面的引用.]
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.]
自從聽到這個(gè)消息后,我發(fā)現(xiàn)這是真的.你怎么看?是否有一個(gè)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?
回應(yīng)一些答案:是的,我理解do/while"和do/while"之間的技術(shù)差異.和同時(shí)".這是一個(gè)涉及循環(huán)的可讀性和結(jié)構(gòu)化代碼的更深層次的問題.
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.
讓我換個(gè)方式問:假設(shè)你被禁止使用do/while"- 是否有一個(gè)現(xiàn)實(shí)的例子,這會(huì)讓你別無選擇,只能使用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:
根據(jù)我的經(jīng)驗(yàn),do-statement 是錯(cuò)誤和混亂的根源.原因是它的主體總是在評(píng)估條件之前執(zhí)行一次.然而,為了讓身體正常工作,即使第一次通過,也必須保持非常類似的情況.比我預(yù)想的更多的是,我發(fā)現(xiàn)無論是在程序第一次編寫和測試時(shí),還是在其前面的代碼被修改之后,這種情況都不會(huì)像預(yù)期的那樣保持.我也更喜歡在我可以看到的地方"的條件.因此,我傾向于避免使用 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 循環(huán)是 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 循環(huán)可以重寫為 while 循環(huán),但是我不同意總是使用 while 循環(huán)更好.do while 總是至少運(yùn)行一次,這是一個(gè)非常有用的屬性(最典型的例子是輸入檢查(從鍵盤))
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');
}
這當(dāng)然可以重寫為 while 循環(huán),但這通常被視為更優(yōu)雅的解決方案.
This can of course be rewritten to a while loop, but this is usually viewed as a much more elegant solution.
這篇關(guān)于是否需要“do {...} while ()"?環(huán)形?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!