开发者

When is a while(True) loop appropriate? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

is while(true) bad programming practice?

What's the point of using “while (true) {…}”?

I've always considered it bad practice to use while(true). Many people think it's okay.

Why would you want to purposefully create an infinite loop? The only two reasons I can think of are:

  1. You're being devious
  2. You're being lazy

When, if ever, is i开发者_StackOverflowt appropriate to use this? And why would you use this over an algorithm?


Sometimes, while(true) is more readable than the alternatives. Case in point:

BufferedReader in = ...;
while (true)
{
  String line = in.readLine();
  if (line == null)
    break;
  process(line);
}

Consider the alternative:

BufferedReader in = ...;
String line;
while ((line = in.readLine) != null)
  process(line);


  • In threaded code (concurrent programming)..

  • In games and for menus

  • While using C or Fortran(I mean moreso here)

Actually you see it a lot...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜