简体   繁体   中英

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.

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:

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:

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 :(");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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