user360907
user360907

Reputation:

do-while condition without declaring a separate variable

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.

Upvotes: 1

Views: 1099

Answers (3)

DavidMFrey
DavidMFrey

Reputation: 1668

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);

Upvotes: 0

Andrew T Finnell
Andrew T Finnell

Reputation: 13628

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);

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

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.

Upvotes: 2

Related Questions