“if”语句末尾的分号 [英] Semicolon at end of 'if' statement

查看:241
本文介绍了“if”语句末尾的分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,经过半小时的搜索错误,我发现可以在if语句后面加一个分号而不是代码,如下所示:

  if(a == b); 
//做东西

这基本上意味着无论是等于b,这些东西都会完成或不,if语句没有任何意义。为什么Java没有给我一个错误?有什么情况可以使用吗?

解决方案

为什么会这样?




  • Checkstyle

  • Pmd



  • 他们可以立即突出显示此问题。


    我建议结合两种解决方案。


    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 == b);
    // Do stuff
    

    Which basically means that the stuff will be done whether a equals b or not, and the if statement has no point whatsoever. Why doesn't Java give me an error? Is there any situation in which this would be useful?

    解决方案

    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:

      They can instantly highlight problems such as this one.

    I would recommend to combine both solutions.

    这篇关于“if”语句末尾的分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆