开发者

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.


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜