while (true) 是否具有破坏不良的编程习惯?

编程入门 行业动态 更新时间:2024-10-19 19:28:55
本文介绍了while (true) 是否具有破坏不良的编程习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-26 03:44:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不良   习惯   true

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!