In the following code, does the break
statement break out of the if
statement only or out of the for
loop too?
I need it to break out of the loop too.
for (int i = 0; i < 5; i++) {
if (i == temp)
// do something
else {
temp = i;
break;
}
}
break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute.
breaks don't break if statements. A developer working on the C code used in the exchanges tried to use a break to break out of an if statement. But break s don't break out of if s. Instead, the program skipped an entire section of code and introduced a bug that interrupted 70 million phone calls over nine hours.
The break statement has no use in decison making statements. It is used only in loops, when you want to force termination from the loop and continue execution from the statement following the loop.
The keyword break works only on the current loop. You can't break the outmost loop from any enclosed loop with a single break , you'll need to set a flag in order to break at start of each loop when it becomes non-null.
That would break out of the for loop. In fact break
only makes sense when talking about loops
, since they break from the loop
entirely, while continue
only goes to the next iteration
.
An unlabelled break
only breaks out of the enclosing switch
, for
, while
or do-while
construct. It does not take if
statements into account.
See http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With