Why does Java allow for labeled breaks on arbitrary statements?

前端 未结 9 2152
爱一瞬间的悲伤
爱一瞬间的悲伤 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:35

    The issue with goto is that it can jump forward, past code. A labeled break cannot do that (it can only go backwards). IIRC C++ has to deal with goto jumping past code (it is been over 17 years since I cared about that though so I am not sure I am remembering that right).

    Java was designed to be used by C/C++ programmers, so many things were done to make it familiar to those developers. It is possible to do a reasonable translation from C/C++ to Java (though some things are not trivial).

    It is reasonable to think that they put that into the language to give C/C++ developers a safe goto (where you can only go backwards in the code) to make it more comfortable to some programmers converting over.

    I have never seen that in use, and I have rarely seen a labeled break at all in 16+ years of Java programming.

    You cannot break forward:

    public class Test 
    {
        public static void main(final String[] argv) 
        {
            int val = 1;
    
            X:
            {
                if(argv.length == 0)
                {
                    break X;
                }
    
                if(argv.length == 1)
                {
                    break Y;   <--- forward break will not compile
                }
            }
    
            val = 0;
    
            Y:
            {
                Sysytem.out.println(val); <-- if forward breaks were allowed this would 
                                              print out 1 not 0.
            }
        }
    }
    

提交回复
热议问题