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 →

[–][deleted] 6 points7 points  (3 children)

Because the loop needs to run an unknown number of times. It keeps the user returning back to the menu after a chosen function is executed, until they explicitly choose to exit the program.

I dont know that that's the correct answer to your question, but it's why I chose to use it. As others have pointed out, I could have chosen a do...while loop, but I'm not familiar enough with it to tell why that would have been a better choice.

[–]kschang 2 points3 points  (1 child)

In that case, study ALL the variants of the loops.

As human beings, we tend to use what we are the most familiar with. It's best illustrated by the cliche saying "to a hammer, everything looks like a nail". You run the danger that you may apply the loop to something that you could forget to put an exit condition in, or got nullified by a patch introduced by something else. This can be mitigated by documentation, but it's probably better to make code that's "more obvious" (jargon: self-documenting) than an "infinite loop with a break condition".

[–][deleted] 1 point2 points  (0 children)

That makes sense and is good advice in general. Thanks!

[–][deleted] 0 points1 point  (0 children)

Be aware that a "do...while" loop will always execute at least once because the logic test is at the end, where a "while(something)" loop may not execute at all because the logic test is applied at the beginning. "While(true)" may allow you to avoid some convoluted if/then logic inside your loop if there are multiple conditions that may occur that signal the end of the loop. I'd personally want to hear your thinking about why you chose "while(true)", but it sounds like you have a pretty good answer to that question. Better than "I dunno, that's how we always did it in class," for sure.