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

夙愿已清 提交于 2020-01-14 06:59:11

问题


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

Is there any way of doing this?


回答1:


Use the break statement.

if (!d) break;

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




回答2:


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



回答3:


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.




回答4:


break;




回答5:


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



回答6:


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



回答7:


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

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



回答8:


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.



来源:https://stackoverflow.com/questions/2649473/is-there-a-way-to-break-out-of-a-while-loop-before-the-original-condition-is-mad

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!