Why does Java allow for labeled breaks on arbitrary statements?

前端 未结 9 1853
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 13:16

I just learned today that the following Java code is perfectly legal:

myBlock: {
    /* ... code ... */

    if (doneExecutingThisBlock())
        break myBlock;         


        
9条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 13:53

    The ability to leave a sequence of statements has been implemented in several programming languages before Java. Two examples:

    Algol-68 had exit to terminate the execution of the smallest closed-clause (very loosely speaking, a begin ... end sequence).

    BLISS had labelled BEGIN … END blocks, with a LEAVE statement to terminate execution.

    Implementations with labels (as in Java) are more flexible in that they can exit nested blocks (or compound statements, or whatever you call them in your language of choice); without the label, you're limited to exiting a single "level" only.

    Answering the direct question, "why" -- because it's been found to be a useful construct in other, prior, languages.

提交回复
热议问题