What condition does while(true) test? When is it true and false?

扶醉桌前 提交于 2020-01-12 06:21:29

问题


I do no understand why anybody would use

while(true) {
   //do something
}

instead of

boolean condition = true;
while(condition == true) {
   //do something
}

The latter is super easy to understand, whilst the former is not.

So, what condition does while(true) check? When is while(true) true, and when is it false?


回答1:


When is while(true) true, and when is it false?

It's always true, it's never false.

Some people use while(true) loops and then use break to exit them when a certain condition is true, but it's generally quite sloppy practice and not recommended. Without the use of break, return, System.exit(), or some other such mechanism, it will keep looping forever.




回答2:


Though we never know when we encounter a situation where we need it. We can also have infinite for loop.

for(;;) {//Code here}



回答3:


condition == true is also going to return a boolean which is 'true'.So using that directly instead of all that.




回答4:


while(true) loop will of course always iterate. You've to manually break out of it using break, or System.exit(), or may be return.

while(condition == true) will be true while condition is true. You can make that false by setting condition = false.

I would never ever use while(condition == true) at least. Instead just use while (condition). That would suffice.




回答5:


while(true) is always true. Loop statements are executed all the time. If you have to break the loop, we have to use break statement.




回答6:


while(true) is used to for infinite loops. They will loop forever because true is ALWAYS true They are generally used when you have to do something until a certain condition is met. You then exit with the break statement

while(true) {
  //attempt to satisfy some condition

  if (satisfied) {
    break;
  }
}



回答7:


  1. List item

while(True): statement if(condition): break This is only work in python In java you can write like that for same purpose

while(1==1) { Ststements... }



来源:https://stackoverflow.com/questions/22512830/what-condition-does-whiletrue-test-when-is-it-true-and-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!