Semicolon at end of 'if' statement

前端 未结 18 1665
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:01

Today, after half an hour of searching for a bug, I discovered that it is possible to put a semicolon after an if statement instead of code, like this:

if(a          


        
18条回答
  •  时光取名叫无心
    2020-11-22 01:22

    A few definitions from the jls explain this (chapter 14):

    Blocks are Statements

    As stated here, a Block is a StatementWithoutTrailingSubstatement, which in turn is a StatementNoShortIf, which is a Statement. Thus where ever any of these is required, we can insert a Block.

    The if-clause

    Though this is as well the case for for and while-loops, I'll use if-statements. These rules are pretty much the same. The syntactical description of if-statements can be found here.

    IfThenStatement:
        if ( Expression ) Statement
    
    IfThenElseStatement:
        if ( Expression ) StatementNoShortIf else Statement
    
    IfThenElseStatementNoShortIf:
        if ( Expression ) StatementNoShortIf else StatementNoShortIf
    

    So we can use our block here.

    But why does it work with ; ?

    ; is defined as the EmptyStatement (link), which is as well a StatementNoShortIf. So in conditional pieces of code, like if-statement and loops, we can replace a Block with a EmptyStatement, if a StatementNoShortIf or Statement is required.

    Thus if(Expression)EmptyStatement works.

    Why doesn't this give an error?

    Pretty simple: java gives an error if it finds invalid syntax. But if(Expression)EmptyStatement is perfectly valid syntax. Instead javac gives a warning if launched with the proper parameters. The full list of warnings that can be dis-/enabled lists the warning-name empty for this purpose. So compilation with -Xlint:all or -Xlint:empty will generate a warning about this.

    Your IDE should have an option to enable this kind of warning as well. For eclipse, see @nullptr's answer. In IntelliJ, you can press Ctrl + Shift + A, enter empty body into the search field and enable the warning (marked in the image)

    What is this even used for?

    To be honest, there's not much use in it from a minimalistic point of view. There's usually a way to get things done without a "do nothing" command. It's rather a question of personal preferences, whether you rather use

    if( a() && b() );
    

    or

    if( a() ) b();
    

    and same would apply to other cases, in which the EmptyStatement is used. An important point to consider on this topic is readability of code. There are occasions, where code becomes more readable by using the no-op. On the other hand there are cases, where code becomes quite a lot harder to comprehend with using the EmptyStatement - the above example would count to the later IMO.

提交回复
热议问题