Question

I have a do-while loop inside a function that resembles something like this:

do
{
    // a bunch of stuff
    if (something < something else)
    {
        return true;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return false;
        }
        else
        {
              return true;
         }
     }
} while (condition);

My issue here is with the condition at the end. The only way I can thing of to keep track of this would be to declare a boolean variable before the loop, and have it's value set to match the return value and have the while() check for that after each iteration. While this would work, it's seems rather inelegant to me and I was wondering if there was a way I could have the while() tap into the return value instead.

Was it helpful?

Solution

Assuming your code is incorrect due to you trying to paraphrase it, this is what you should be doing to meet your needs of the return being the same as the while();

To others, this code below is incorrect logic, but I am trying to keep it in the similar pseudo code he utilized. Basically if you want the while to mimic the return value, you need the ! of the return in order for the condition to exit.

do
{
    // a bunch of stuff
    if (something < something else)
    {
        return !condition;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return condition;
        }
        else
        {
              return !condition;
        }
    }
} while (condition);

OTHER TIPS

It’s not clear how your condition looks like. Anyway, you probably want an infinite loop:

for (; ;) {
    … your code here …
}

or:

while (true) {
    … your code here …
}

This loop will never stop by itself … but since you exit it using return this isn’t a problem.

You could just say

 do
{
    // a bunch of stuff
    if (something < something else)
    {
        return true;
    }
    else if (stuff > other stuff)
    {
        if (something != other stuff)
        {
             return false;
        }
        else
        {
              return true;
         }
     }
     else if(exit_condition)
      break;
} while (1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top