开发者

Is there a way to break out of a while loop before the original condition is made false?

Is there a way to break out of a while loop before the original condition is made false?

for example if i have:

while (a==true) 
{ 
    doSomething() ; 
    if (d==false) get out of loop ;
    doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true(开发者_如何学Go) ;
} 

Is there any way of doing this?


Use the break statement.

if (!d) break;

Note that you don't need to compare with true or false in a boolean expression.


break is the command you're looking for.

And don't compare to boolean constants - it really just obscures your meaning. Here's an alternate version:

while (a) 
{ 
    doSomething(); 
    if (!d)
        break;
    doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true();
} 


Try this:

if(d==false) break;

This is called an "unlabeled" break statement, and its purpose is to terminate while, for, and do-while loops.

Reference here.


break;


Yes, use the break statement.

while (a==true) 
{ 
    doSomething() ; 
    if (d==false) break;
    doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true() ;
} 


while(a)
{
    doSomething();
    if(!d)
    {
        break;
    }
}


Do the following Note the inclusion of braces - its good programming practice

while (a==true) 
{ 
    doSomething() ; 
    if (d==false) { break ; }
    else { /* Do something else */ }
} 


while ( doSomething() && doSomethingElse() );

change the return signature of your methods such that d==doSomething() and a==doSomethingElse(). They must already have side-effects if your loop ever escapes.

If you need an initial test of so value as to whether or not to start the loop, you can toss an if on the front.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜