简体   繁体   English

为什么我会收到警告“死码”?

[英]Why am I get a warning “Dead code”?

    if (myCondition1 && myCondition2 && myCondition3)
    {
    ...
    }

I wrote this code and run successfully. 我编写了这段代码并成功运行。 but I got warning about part of (...). 但我对(...)的一部分发出了警告。 The warning is "Dead code". 警告是“死代码”。 It is just interesting to me. 这对我来说很有趣。 Do u have any idea? 你有什么想法吗? thank u 感谢你

"Dead code" is code that will never be executed. “死代码”是永远不会被执行的代码。 Most likely one of your conditions is hard-coded to false somewhere, making the conditional inside the if always false. 很可能你的某个条件在某处被硬编码为false ,使条件内的if始终为false。

Dead code means it is never going to execute. 死代码意味着永远不会执行。 Eg 例如

void someMethod() {
    System.out.println("Some text");
    return;
    System.out.println("Another Some text"); // this is dead code, because this will never be printed
}

Same in case of your condition checking eg 在您的状况检查时也是如此

String obj = "";
if(obj == null && obj.equals("")) { // here you get warning for Dead code because obj is not null and first condition is false so obj.equals("") will never evaluate

}

Your code inside the block is never reached. 永远不会到达块中的代码。 The reason is most likely that one of the conditions is always false. 原因很可能是其中一个条件总是错误的。

如果myCondition1,myCondition2和myCondition3中的一个或多个始终为false(如私有const bool myCondition1 = false;)那么if中的代码将永远不会被执行。

This could occur for a number of reasons. 这可能由于多种原因而发生。 Either the whole of the if block is dead , caused by something like the following: 整个if块都死了 ,由以下内容引起:

boolean condition1 = true;
boolean condition 2 = !condition1;

if(condition1 && condition2) {
    //This code is all dead
    Foo f = fooFactory();
    f.barr(new Bazz());
}

Or you unconditionally leave the if block using something like return , break or continue , as shown below: 或者你无条件地使用returnbreakcontinue类的东西离开if块,如下所示:

for(Foo f : foos) {
    if(true) {
        f.barr(new Bazz());
        break;
        //Everything after here is dead
        System.out.println("O noes. I won't get printed :(");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM