问题描述
限时送ChatGPT账号..我经常使用这种代码模式:
I often use this code pattern:
while(true) {
//do something
if(<some condition>) {
break;
}
}
另一位程序员告诉我这是不好的做法,我应该用更标准的方式替换它:
Another programmer told me that this was bad practice and that I should replace it with the more standard:
while(!<some condition>) {
//do something
}
他的理由是,你可能太容易忘记休息时间",从而导致无限循环.我告诉他,在第二个例子中,你可以很容易地放入一个永远不会返回 true 的条件,因此很容易出现无限循环,所以两者都是同样有效的做法.
His reasoning was that you could "forget the break" too easily and have an endless loop. I told him that in the second example you could just as easily put in a condition which never returned true and so just as easily have an endless loop, so both are equally valid practices.
此外,我通常更喜欢前者,因为当您有多个断点(即退出循环的多个条件)时,它使代码更易于阅读.
Further, I often prefer the former as it makes the code easier to read when you have multiple break points, i.e. multiple conditions which get out of the loop.
任何人都可以通过为一方或另一方添加证据来丰富这个论点吗?
Can anyone enrichen this argument by adding evidence for one side or the other?
推荐答案
这两个示例之间存在差异.即使语句永远不会正确,第一个也会每次至少执行一次做某事".第二个只会在语句评估为真时做某事".
There is a discrepancy between the two examples. The first will execute the "do something" at least once every time even if the statement is never true. The second will only "do something" when the statement evaluates to true.
我认为您正在寻找的是一个 do-while 循环.我 100% 同意 while (true)
不是一个好主意,因为它很难维护此代码,而且您逃避循环的方式非常 goto
被认为是不好的做法.
I think what you are looking for is a do-while loop. I 100% agree that while (true)
is not a good idea because it makes it hard to maintain this code and the way you are escaping the loop is very goto
esque which is considered bad practice.
试试:
do {
//do something
} while (!something);
检查您的个人语言文档以了解确切的语法.但是看看这段代码,它基本上做了do里面的事情,然后检查while部分看是否应该再做一次.
Check your individual language documentation for the exact syntax. But look at this code, it basically does what is in the do, then checks the while portion to see if it should do it again.
这篇关于while (true) 是否具有破坏不良的编程习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论