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

Is there any way of doing this?

3

8 Answers

Use the break statement.

if (!d) break;

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

1

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.

1

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like