views:

153

answers:

8

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?

+3  A: 

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();
} 
Carl Manaster
+1  A: 

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() ;
} 
JG
+2  A: 

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.

Matthew Jones
You shouldn't promote usage of `== false` (and `== true` and `!= false` and `!= true`).
polygenelubricants
+2  A: 

break;

Ben S
+9  A: 

Use the break statement.

if (!d) break;

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

BalusC
You may not need to, but you might want to for readability.
Matthew Jones
@Matt: For that I'd rather rename the variable name into something more sensitive :)
BalusC
@BalusC + 1 for your comment
hhafez
+1  A: 
while(a)
{
    doSomething();
    if(!d)
    {
        break;
    }
}
mportiz08
A: 

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

while (a==true) 
{ 
    doSomething() ; 
    if (d==false) { break ; }
    else { /* Do something else */ }
} 
Chris
A: 
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.

Carl