Semicolon at end of 'if' statement

前端 未结 18 1505
没有蜡笔的小新
没有蜡笔的小新 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:20

    While working on a programming assignment for class where I am working with a N by N grid of doodads and comparing characteristics of a random doodad to those above, below, left, and right, I found a nice use of this to prevent nested statements and potential boundary exceptions. My goal was to minimize code and keep from nesting if-statements.

    if (row == 0); 
    else (method (grid[row][col], grid[row-1][col]));
    if (row == N-1);
    else (method (grid[row][col], grid[row+1][col]));
    if (col == 0);
    else (method (grid[row][col], grid[row][col-1]));
    if (col == N-1);<br>
    else (method (grid[row][col], grid[row][col+1]));
    

    where method(Doodad a, Doodad b) does some operation between a and b.

    Alternatively, you could use exception handling to avoid this syntax, but it works and works well for my application.

    0 讨论(0)
  • 2020-11-22 01:21

    A possible use case:

    if (a==b);
    else {
      // Do something
    }
    

    Not good, but possible.

    Still, I do think that the Java specification should disallow an empty if.

    0 讨论(0)
  • 2020-11-22 01:21

    Just a FYI about the usability and what difference it makes or can make if there is a statement like that

    Consider a piece of code like the following.

    int a = 10;
    if ((a = 50) == 50);
    
    System.out.println("Value of a = " + a);
    

    Clearly in this case, the if statement does change the output. So a statement like that can make a difference.

    This is a situation where this could be useful or better to say have an impact on program.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 01:23

    Why does it happen?

    Java Language Specification says that:

    The Empty Statement

    An empty statement does nothing.

    EmptyStatement:
        ;
    

    Execution of an empty statement always completes normally

    It essentially means that you want to execute empty statement if a==b

    if(a == b);
    

    What should you do:

    There are two main solutions to this problem:

    1. You can avoid problems with empty statement by using code formatter and surrounding stuff inside if with { and }. By doing this Your empty statement will be much more readable.

      if(a == b){
        ;
      }
      
    2. You can also check tools used for static code analysis such as:

      • Findbugs
      • Checkstyle
      • Pmd

      They can instantly highlight problems such as this one.

    I would recommend to combine both solutions.

    0 讨论(0)
  • 2020-11-22 01:26

    I can think of a scenario where an empty statement is required (not for if condition but for while loop).

    When a program just want an explicit confirmation from the user to proceed. This may be required when the work after the user confirmation depends on some other things and user want to take control of when to proceed.

        System.out.println("Enter Y to proceed. Waiting...");
        System.out.println("");
    
        while(!(new Scanner(System.in).next().equalsIgnoreCase("Y")));
    
        System.out.println("Proceeding...");
        // do the work here
    
    0 讨论(0)
提交回复
热议问题