Does the break statement break out of loops or only out of if statements?

◇◆丶佛笑我妖孽 提交于 2019-11-27 17:55:55

问题


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

回答1:


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.




回答2:


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.




回答3:


It also goes out of the loop.

You can also use labeled breaks that can break out of outer loops (and arbitrary code blocks).

looplbl: for(int i=;i<;i++){

    if (i == temp)
        // do something
    else {
        temp = i;
        break looplbl;
    }
}



回答4:


It breaks the loop, but why not explicitly put the condition in the for itself? It would be more readable and you would not have to write the if statement at all

(if i==temp then temp = i is totally pointless)




回答5:


It will break out of the loop always.




回答6:


Break never refers to if/else statements. It only refers to loops (if/while) and switch statements.




回答7:


break is to break out of any loop.




回答8:


Generally break statement breaks out of loops (for, while, and do...while) and switch statements.

In Java there are 2 variant of break.

1. Labeled break

It break outs of the outer loop where you put the lable.

breakThis: for(...){
   for(...){
      ... 
      break breakThis;  // breaks the outer for loop
   }
}

2. Unlabeled break

It is the statement you used in your question.

It breaks the loop in which it is written. Generally inner loop.




回答9:


It would break you out of the for loop. Generally break statement is used to optimise the running time of your program. Means when the given condition is met, use break statement so that it will take you out of the loop and ignores the remaining iterations.



来源:https://stackoverflow.com/questions/7289938/does-the-break-statement-break-out-of-loops-or-only-out-of-if-statements

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