Can java labels be used appropriately outside of for loops?

前端 未结 2 1177
野趣味
野趣味 2020-12-20 21:53

So I\'ve seen a lot of cases where labels are being used in for loops to break out, especially with doubly nested loops.

Is this the only case where they can be used

2条回答
  •  攒了一身酷
    2020-12-20 22:52

    It is fair to say that labeling a loop is the only useful way that a labeled statement can be used.

    You are allowed to label any statement in Java, but the only way they are used is as a target of a (labeled) break or continue statement.

    The usual advice applies though: just because you can do something does not mean you should. Don't use labels as funny "comments" (yes I have seen this done). Don't write doubly nested loops just to show off your ability to break or continue an outer loop. These days we tend to favor operations that apply to a whole sequence, mitigating some uses for labeled breaks and continues. As always, aim for readability and simplicity. That said, tools like parser generators that output Java source are quite likely to make heavy use of labeled statements, even if human programmers rarely do.

提交回复
热议问题