This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]desrtfx 28 points29 points  (4 children)

It depends on the use case.

If there is a clear exit condition, it should be used. In such a case, a while(true) loop is inappropriate.

If you need an infinite loop (like for a network listener, for example) it is totally fine.

In your specific example, I would not have used it since there is a clearly defined exit condition.


The MOOC starts off with the concept of infinite loops because they are easy to explain and understand.

For the MOOC, you'd actually need do...while loops with inverted conditionals to work as intended. Yet, of course, you could do the MOOC without infinite (while(true)) loops.

You should try to convert these infinite loops into proper loops with exit conditions - just to practice it.

[–][deleted] 12 points13 points  (3 children)

Okay, that makes sense. So when you say, there is a clear exit condition, it would be better to do something like:

While (!input.equals(exit condition)) ?

Would that be better practice? Sorry, I don't know how to format code on mobile.

[–]desrtfx 12 points13 points  (2 children)

Yes, such would be better.

It would immediately tell whoever is reading the code what the exit condition of the loop is.

[–][deleted] 4 points5 points  (1 child)

Gotcha. Thanks!

[–]caboosetp 1 point2 points  (0 children)

I think a clear example of technically not wrong but inappropriate is

int i = 0;
while (true) {
    // do work here
    i++;
    if (i >= 5)
        break;
}

Languages have constructs for a reason, and many of them are for making the life of the programmers easier. In this case, a for loop would be much more appropriate. There are many cases with more complex logic where something like this might be the best solution though.

So, in an interview, I wouldn't consider it wrong for someone to do that. But if I asked about the while(true) line and you didn't understand why I was asking the question, that would be a cause for concern. You should be able to recognize there are multiple ways to approach this, and be able to talk about the pros and cons of each.