简体   繁体   English

有没有办法在原始条件变为假之前突破while循环?

[英]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? 有没有办法在原始条件变为假之前突破while循环?

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? 有没有办法做到这一点?

Use the break statement . 使用break语句

if (!d) break;

Note that you don't need to compare with true or false in a boolean expression. 请注意,您不需要在布尔表达式中与truefalse进行比较。

break is the command you're looking for. break是你正在寻找的命令。

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. 这称为“未标记”的break语句,其目的是终止whilefordo-while循环。

Reference here . 参考这里

Yes, use the break statement. 是的,使用break语句。

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() . 更改方法的返回签名,例如d==doSomething()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. 如果您需要对是否启动循环进行初始测试,可以在前面抛出一个if

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM