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

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

问题描述

今天找了半个小时的bug,发现可以在if语句后加分号代替代码,像这样:

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

这基本上意味着无论 a 是否等于 b 都会完成这些事情,并且 if 语句没有任何意义.为什么Java不给我一个错误?在任何情况下这会有用吗?

解决方案

为什么会这样?

  • 检查风格
  • 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天全站免登陆