0

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 it appropriate to use this? And why would you use this over an algorithm?

Community
  • 1
  • 1
Cody
  • 8,686
  • 18
  • 71
  • 126
  • "why would you use this over an algorithm": Umm... you can use it as *part* of an algorithm. The two aren't mutually exclusive. – flight Sep 27 '11 at 03:00
  • I'm asking when it's appropriate..not whether it is bad or not - just reasons for why exactly it could be used. – Cody Sep 27 '11 at 03:03
  • @DoctorOreo Judge the worth of an resolved question by it's answers not by the title. – flight Sep 27 '11 at 03:04
  • BTW, it's not called "being lazy" , it's called saving time for sleep! – Caffeinated Sep 27 '11 at 03:05

2 Answers2

5

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);
Gili
  • 86,244
  • 97
  • 390
  • 689
1
  • 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...

Caffeinated
  • 11,982
  • 40
  • 122
  • 216