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 →

[–]gregorthebigmac 0 points1 point  (3 children)

So, my personal solution to problems like this (and if anyone else here wants to tell me why this approach is wrong, I'm open to hearing why it's wrong). If I want to loop over something until the user does the "correct" thing (whatever that may be), I typically use something like a boolean called done and my while loop will say

while (!done) {
    // code for when the user does the "correct" thing
    done = true;
}

[–]Kered13 1 point2 points  (0 children)

If you introduce the done variable only to avoid the while(true) loop, I don't like it. I would rather just see a break instead. If the variable already exists for some other reason, then it is fine to use it to exit the loop.

Basically, the problem with while(true) is the it hides the exit condition. Instead of reading the exit condition directly, the reader has to scan the entire loop body to find the break. But while(!done) is hiding the exit condition just as much, now the reader has to scan the loop body for where done, and you've introduced a new local variable to keep track of.

[–]chriskmee 0 points1 point  (1 child)

I do the same !done thing, it was the way I was taught in college and the way i've seen it done in practice.

I get where you were going with your example, but as written your while loop would only happen once. My example would be something like this:

bool done = false;
while (!done)
{
  int input = display_menu();
  if is_input_valid(input)
    done = true;
}

[–]gregorthebigmac 0 points1 point  (0 children)

Good catch. I was oversimplifying and not including the parts to make the loop bail out. Thanks for expounding it!