Semicolon at end of 'if' statement

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

提交回复
热议问题