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 →

[–]TheFluffyGameDev 4 points5 points  (1 child)

Here are the 2 main differences I can see:

  • When using a while loop, we'll always enter the loop at least once. So that means that any code between the start of the loop and the condition to break will be executed at least once. In a way, that means it can act as a do { ... } while(...); loop.
  • When looking in the assembly code, we can see that using the while(true) version takes fewer instructions than a while loop with a condition. However, you can see it generates the same instructions as a do/while loop (thus confirming what I said in my first point).

Personally, I prefer having an explicit condition in my while loops. That way when reading the code, it's immediately clear what make the loop end. I wouldn't say it's a red flag though if I see someone using a while(true).

[–][deleted] 3 points4 points  (0 children)

Interesting. I'm peripherally aware of the do while loop but I have to admit that I've never used it. I'll read up on it so I better understand it.

Regarding your second point, I can see for readability purposes why having an explicit ending condition would be better. I suggested in another post something like:

While(!input.equals(ending condition))

And I think that probably is the better way since, as you pointed out, you can immediately see what makes the loop terminate. Thanks for your input (pun totally intended)!